Skip to content

Commit 395ab97

Browse files
authored
Merge pull request #90 from vuex-orm/82-89-warn-on-non-insertable-response-data
#82 #89 Warn users when the response data is not insertable
2 parents fb1bf01 + 4a46cb2 commit 395ab97

File tree

3 files changed

+36
-4
lines changed

3 files changed

+36
-4
lines changed

src/api/Request.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -148,7 +148,7 @@ export default class Request {
148148
return response
149149
}
150150

151-
config.save && response.save()
151+
config.save && await response.save()
152152

153153
return response
154154
}

src/api/Response.ts

Lines changed: 16 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -41,9 +41,15 @@ export default class Response {
4141
* Save response data to the store.
4242
*/
4343
async save (): Promise<void> {
44-
this.entities = await this.model.insertOrUpdate({
45-
data: this.getDataFromResponse()
46-
})
44+
const data = this.getDataFromResponse()
45+
46+
if (!this.validateData(data)) {
47+
console.warn('[Vuex ORM Axios] The response data could not be saved to the store because it\'s not an object or an array. You might want to use `dataTransformer` option to handle non-array/object response before saving it to the store.')
48+
49+
return
50+
}
51+
52+
this.entities = await this.model.insertOrUpdate({ data })
4753

4854
this.isSaved = true
4955
}
@@ -75,4 +81,11 @@ export default class Response {
7581

7682
return this.response.data
7783
}
84+
85+
/**
86+
* Validate if the given data is insertable to Vuex ORM.
87+
*/
88+
private validateData (data: any): data is Record | Record[] {
89+
return data !== null && typeof data === 'object'
90+
}
7891
}

test/feature/Response_Save.spec.ts

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,25 @@ describe('Feature - Response - Save', () => {
2020
beforeEach(() => { mock = new MockAdapter(axios) })
2121
afterEach(() => { mock.reset() })
2222

23+
it('warns the user if the response data is not insertable', async () => {
24+
const spy = jest.spyOn(console, 'warn')
25+
26+
spy.mockImplementation(x => x)
27+
28+
createStore([User])
29+
30+
mock.onGet('/api/users').reply(200, null)
31+
await User.api().get('/api/users')
32+
33+
mock.onGet('/api/users').reply(200, 1)
34+
await User.api().get('/api/users')
35+
36+
expect(console.warn).toHaveBeenCalledTimes(2)
37+
38+
spy.mockReset()
39+
spy.mockRestore()
40+
})
41+
2342
it('can save response data afterword', async () => {
2443
mock.onGet('/api/users').reply(200, { id: 1, name: 'John Doe' })
2544

0 commit comments

Comments
 (0)