diff --git a/src/jsonapi-datastore.js b/src/jsonapi-datastore.js index 022ee33..0fb3fd8 100644 --- a/src/jsonapi-datastore.js +++ b/src/jsonapi-datastore.js @@ -202,6 +202,16 @@ class JsonApiDataStore { }; } + formatErrors(payload) { + return payload.errors.map(function(error) { + return { + status: error.status, + attribute: error.source.pointer.split('/')[3], + detail: error.detail + }; + }) + }; + /** * Sync a JSONAPI-compliant payload with the store. * @method sync @@ -209,6 +219,10 @@ class JsonApiDataStore { * @return {object} The model/array of models corresponding to the payload's primary resource(s). */ sync(payload) { + if (payload.errors) { + return { errors: this.formatErrors(payload) }; + } + return this.syncWithMeta(payload).data; } } diff --git a/test/store.spec.js b/test/store.spec.js index 79f79b0..98de47c 100644 --- a/test/store.spec.js +++ b/test/store.spec.js @@ -206,6 +206,28 @@ describe('JsonApiDataStore', () => { expect(articles[1].related_article.id).to.eq(1337); }); }); + + context('when given a payload with errors', () => { + var store = new JsonApiDataStore(), + payload = { + errors: [ + { + status: 422, + source: { + pointer: '/data/attributes/title' + }, + detail: 'is too short (minimum is 3 characters)' + } + ] + }; + + it('should return error object', () => { + var articleErrors = store.sync(payload).errors; + expect(articleErrors[0].status).to.eq(422); + expect(articleErrors[0].attribute).to.eq('title'); + expect(articleErrors[0].detail).to.eq('is too short (minimum is 3 characters)'); + }); + }); }); describe('.syncWithMeta()', () => {