Skip to content

Commit

Permalink
Merge pull request #3030 from bdvholmes/ams_camelized_errors
Browse files Browse the repository at this point in the history
ActiveModelAdapter camelizes keys for errors on 422
  • Loading branch information
fivetanley committed Apr 29, 2015
2 parents d11a412 + c947e25 commit 6d47319
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 3 deletions.
15 changes: 14 additions & 1 deletion packages/activemodel-adapter/lib/system/active-model-adapter.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {pluralize} from "ember-inflector";
@module ember-data
*/

var camelize = Ember.String.camelize;
var decamelize = Ember.String.decamelize;
var underscore = Ember.String.underscore;

Expand Down Expand Up @@ -141,7 +142,19 @@ var ActiveModelAdapter = RESTAdapter.extend({
var error = this._super.apply(this, arguments);

if (jqXHR && jqXHR.status === 422) {
return new InvalidError(Ember.$.parseJSON(jqXHR.responseText));
var response = Ember.$.parseJSON(jqXHR.responseText);
var errors = response.errors ? response.errors : response;

for (var underscoredError in errors) {
var camelizedError = camelize(underscoredError);

if (camelizedError !== underscoredError) {
errors[camelizedError] = errors[underscoredError];
delete errors[underscoredError];
}
}

return new InvalidError(errors);
} else {
return error;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@ test('buildURL - decamelizes names', function() {
});

test('ajaxError - returns invalid error if 422 response', function() {
var error = new DS.InvalidError({ errors: { name: "can't be blank" } });
var error = new DS.InvalidError({ name: "can't be blank" });

var jqXHR = {
status: 422,
Expand All @@ -31,8 +31,19 @@ test('ajaxError - returns invalid error if 422 response', function() {
equal(adapter.ajaxError(jqXHR), error.toString());
});

test('ajaxError - accepts any kind of json on 422', function() {
var error = new DS.InvalidError({ name: "can't be blank" });

var jqXHR = {
status: 422,
responseText: JSON.stringify({ name: "can't be blank" })
};

equal(adapter.ajaxError(jqXHR), error.toString());
});

test('ajaxError - invalid error has camelized keys', function() {
var error = new DS.InvalidError({ errors: { firstName: "can't be blank" } });
var error = new DS.InvalidError({ firstName: "can't be blank" });

var jqXHR = {
status: 422,
Expand Down

0 comments on commit 6d47319

Please sign in to comment.