Reputation: 366
My code for saving document to API looks like that
save(category) {
category.save().then(() => {
this.transitionTo('categories');
}).catch((adapterError) => {
console.log(category.get('errors').toArray());
console.log(category.get('isValid'));
});
},
When API answers is:
{"errors":[{"attribute":"name","message":"This value should not be blank."}]}
then
category.get('isValid')
still returns true.
My question is, how validation errors should looks like?
Upvotes: 0
Views: 785
Reputation: 1472
By default, ember-data's adapter determines that a response is invalid when the status code is 422. You can override the isInvalid
function of the adapter to change this.
Also, ember-data now expects errors to be formatted into a json-api error object. If your backend doesn't return it in this format, you can transform it in ember by overriding the handleResponse
function of the adapter.
This is a sample json-api error:
{"errors": [
{
"detail": "Must be unique",
"source": { pointer: "/data/attributes/title"}
},
{
"detail": "Must not be blank",
"source": { pointer: "/data/attributes/content"}
}
]}
If you're returning error responses you described above, you would have to do something like this in your adapter:
handleResponse(status, headers, payload) {
if (status === 422 && payload.errors) {
let jsonApiErrors = [];
for (let key in payload.errors) {
for (let i = 0; i < payload.errors[key].length; i++) {
jsonApiErrors.push({
detail: payload.errors[key][i],
source: {
pointer: `data/attributes/${key}`
}
});
}
}
return new DS.InvalidError(jsonApiErrors);
} else {
return this._super(...arguments);
}
}
Upvotes: 1