diff --git a/src/api/Request.ts b/src/api/Request.ts index 4d6e74d..5aca357 100644 --- a/src/api/Request.ts +++ b/src/api/Request.ts @@ -148,7 +148,7 @@ export default class Request { return response } - config.save && response.save() + config.save && await response.save() return response } diff --git a/src/api/Response.ts b/src/api/Response.ts index 9b9283c..d00c7bc 100644 --- a/src/api/Response.ts +++ b/src/api/Response.ts @@ -41,9 +41,15 @@ export default class Response { * Save response data to the store. */ async save (): Promise { - 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 } @@ -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' + } } diff --git a/test/feature/Response_Save.spec.ts b/test/feature/Response_Save.spec.ts index a6b5dbd..f6e590c 100644 --- a/test/feature/Response_Save.spec.ts +++ b/test/feature/Response_Save.spec.ts @@ -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' })