Skip to content

Commit

Permalink
Merge pull request #90 from vuex-orm/82-89-warn-on-non-insertable-res…
Browse files Browse the repository at this point in the history
…ponse-data

#82 #89 Warn users when the response data is not insertable
  • Loading branch information
kiaking authored Nov 18, 2019
2 parents fb1bf01 + 4a46cb2 commit 395ab97
Show file tree
Hide file tree
Showing 3 changed files with 36 additions and 4 deletions.
2 changes: 1 addition & 1 deletion src/api/Request.ts
Original file line number Diff line number Diff line change
Expand Up @@ -148,7 +148,7 @@ export default class Request {
return response
}

config.save && response.save()
config.save && await response.save()

return response
}
Expand Down
19 changes: 16 additions & 3 deletions src/api/Response.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,15 @@ export default class Response {
* Save response data to the store.
*/
async save (): Promise<void> {
this.entities = await this.model.insertOrUpdate({
data: this.getDataFromResponse()
})
const data = this.getDataFromResponse()

if (!this.validateData(data)) {
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.')

return
}

this.entities = await this.model.insertOrUpdate({ data })

this.isSaved = true
}
Expand Down Expand Up @@ -75,4 +81,11 @@ export default class Response {

return this.response.data
}

/**
* Validate if the given data is insertable to Vuex ORM.
*/
private validateData (data: any): data is Record | Record[] {
return data !== null && typeof data === 'object'
}
}
19 changes: 19 additions & 0 deletions test/feature/Response_Save.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,25 @@ describe('Feature - Response - Save', () => {
beforeEach(() => { mock = new MockAdapter(axios) })
afterEach(() => { mock.reset() })

it('warns the user if the response data is not insertable', async () => {
const spy = jest.spyOn(console, 'warn')

spy.mockImplementation(x => x)

createStore([User])

mock.onGet('/api/users').reply(200, null)
await User.api().get('/api/users')

mock.onGet('/api/users').reply(200, 1)
await User.api().get('/api/users')

expect(console.warn).toHaveBeenCalledTimes(2)

spy.mockReset()
spy.mockRestore()
})

it('can save response data afterword', async () => {
mock.onGet('/api/users').reply(200, { id: 1, name: 'John Doe' })

Expand Down

0 comments on commit 395ab97

Please sign in to comment.