From f5c3ffa6b94834c6069fef15c0f32ebe51ba84fc Mon Sep 17 00:00:00 2001 From: Jacob Burenstam Date: Sat, 2 Apr 2016 16:56:23 +0200 Subject: [PATCH] Add payload error parsing --- src/jsonapi-datastore.js | 14 ++++++++++++++ test/store.spec.js | 22 ++++++++++++++++++++++ 2 files changed, 36 insertions(+) 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()', () => {