-
Notifications
You must be signed in to change notification settings - Fork 324
/
application.js
79 lines (72 loc) · 2.53 KB
/
application.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
import RESTAdapter from '@ember-data/adapter/rest';
import flatten from 'lodash-es/flatten';
import isArray from 'lodash-es/isArray';
import isPlainObject from 'lodash-es/isPlainObject';
import isString from 'lodash-es/isString';
export default RESTAdapter.extend({
// Build the URL using the customizable "urlRoot" attribute that can be set
// on the model class.
buildURL(modelName, id, snapshot) {
if(snapshot && snapshot.type && snapshot.type.urlRoot) {
let url = snapshot.type.urlRoot;
if(id) {
url += '/' + encodeURIComponent(id);
}
return url;
} else {
return this._super(...arguments);
}
},
// Ember data requires that errors from the API be returned as an array. This
// normalizes some of our different error responses, so they're always an
// array.
handleResponse(status, headers, payload) {
if(!this.isSuccess(status, headers, payload)) {
this.normalizePayloadErrors(payload, 'errors');
this.normalizePayloadErrors(payload, 'error');
}
return this._super(...arguments);
},
normalizePayloadErrors(payload, key) {
if(payload && payload[key]) {
let rawErrors = payload[key];
let normalizedErrors = [];
if(isArray(rawErrors)) {
// If an array is returned by the API, no need to process further.
normalizedErrors = rawErrors;
} else if(isPlainObject(rawErrors)) {
// Turn an object of error messages into an array of error objects.
for(let field in rawErrors) {
// The value might be an array of error messages.
let messages = flatten([rawErrors[field]]);
messages.forEach(function(message) {
normalizedErrors.push({
field: field,
message: message,
});
});
}
} else if(isString(rawErrors)) {
// Turn a single string error into an array.
normalizedErrors = [{
message: rawErrors,
}];
} else {
// If we have some other type of error response, add an "Unexpected
// error" message.
normalizedErrors = [{
message: 'Unexpected error',
}];
}
if(key === 'errors') {
payload.errors = normalizedErrors;
} else {
// When normalizing another key, like "error", append it to any
// existing items on the expected "errors" attribute.
let existingErrors = payload.errors || [];
payload.errors = existingErrors.concat(normalizedErrors);
delete payload[key];
}
}
},
});