Skip to content

Commit

Permalink
Merge pull request #3909 from adam-knights/json-api-error-no-attribute
Browse files Browse the repository at this point in the history
[BUGFIX beta] Correctly handle object level errors in json api
  • Loading branch information
bmac committed Nov 11, 2015
2 parents aa18100 + 7efa9db commit 309d481
Show file tree
Hide file tree
Showing 2 changed files with 42 additions and 2 deletions.
17 changes: 15 additions & 2 deletions packages/ember-data/lib/adapters/errors.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
const EmberError = Ember.Error;

const SOURCE_POINTER_REGEXP = /^\/?data\/(attributes|relationships)\/(.*)/;
const SOURCE_POINTER_PRIMARY_REGEXP = /^\/?data/;
const PRIMARY_ATTRIBUTE_KEY = 'base';

/**
@class AdapterError
Expand Down Expand Up @@ -115,11 +117,17 @@ export function errorsHashToArray(errors) {
Object.keys(errors).forEach((key) => {
let messages = Ember.makeArray(errors[key]);
for (let i = 0; i < messages.length; i++) {
let title = 'Invalid Attribute';
let pointer = `/data/attributes/${key}`;
if (key === PRIMARY_ATTRIBUTE_KEY) {
title = 'Invalid Document';
pointer = `/data`;
}
out.push({
title: 'Invalid Attribute',
title: title,
detail: messages[i],
source: {
pointer: `/data/attributes/${key}`
pointer: pointer
}
});
}
Expand All @@ -143,6 +151,11 @@ export function errorsArrayToHash(errors) {

if (key) {
key = key[2];
} else if (error.source.pointer.search(SOURCE_POINTER_PRIMARY_REGEXP) !== -1) {
key = PRIMARY_ATTRIBUTE_KEY;
}

if (key) {
out[key] = out[key] || [];
out[key].push(error.detail || error.title);
}
Expand Down
27 changes: 27 additions & 0 deletions packages/ember-data/tests/unit/adapter-errors-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -47,11 +47,33 @@ var errorsArray = [
}
];

var errorsPrimaryHash = {
base: ['is invalid', 'error message']
};

var errorsPrimaryArray = [
{
title: 'Invalid Document',
detail: 'is invalid',
source: { pointer: '/data' }
},
{
title: 'Invalid Document',
detail: 'error message',
source: { pointer: '/data' }
}
];

test("errorsHashToArray", function() {
var result = DS.errorsHashToArray(errorsHash);
deepEqual(result, errorsArray);
});

test("errorsHashToArray for primary data object", function() {
var result = DS.errorsHashToArray(errorsPrimaryHash);
deepEqual(result, errorsPrimaryArray);
});

test("errorsArrayToHash", function() {
var result = DS.errorsArrayToHash(errorsArray);
deepEqual(result, errorsHash);
Expand All @@ -67,6 +89,11 @@ test("errorsArrayToHash without trailing slash", function() {
deepEqual(result, { name: ['error message'] });
});

test("errorsArrayToHash for primary data object", function() {
var result = DS.errorsArrayToHash(errorsPrimaryArray);
deepEqual(result, errorsPrimaryHash);
});

test("DS.InvalidError will normalize errors hash will assert", function() {
var error;

Expand Down

0 comments on commit 309d481

Please sign in to comment.