Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ActiveModelAdapter camelizes keys for errors on 422 #3030

Merged
merged 3 commits into from Apr 29, 2015
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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