This repository has been archived by the owner on Jan 30, 2023. It is now read-only.
-
-
Notifications
You must be signed in to change notification settings - Fork 87
/
ajax.js
281 lines (241 loc) · 7.26 KB
/
ajax.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
import Ember from 'ember';
import {
AjaxError,
UnauthorizedError,
InvalidError,
ForbiddenError
} from '../errors';
import parseResponseHeaders from '../utils/parse-response-headers';
const {
deprecate,
get
} = Ember;
/**
### Headers customization
Some APIs require HTTP headers, e.g. to provide an API key. Arbitrary
headers can be set as key/value pairs on the `RESTAdapter`'s `headers`
object and Ember Data will send them along with each ajax request.
```app/services/ajax
import AjaxService from 'ember-ajax/services/ajax';
export default AjaxService.extend({
headers: {
"API_KEY": "secret key",
"ANOTHER_HEADER": "Some header value"
}
});
```
`headers` can also be used as a computed property to support dynamic
headers.
```app/services/ajax.js
import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';
export default AjaxService.extend({
session: Ember.inject.service(),
headers: Ember.computed("session.authToken", function() {
return {
"API_KEY": this.get("session.authToken"),
"ANOTHER_HEADER": "Some header value"
};
})
});
```
In some cases, your dynamic headers may require data from some
object outside of Ember's observer system (for example
`document.cookie`). You can use the
[volatile](/api/classes/Ember.ComputedProperty.html#method_volatile)
function to set the property into a non-cached mode causing the headers to
be recomputed with every request.
```app/services/ajax.js
import Ember from 'ember';
import AjaxService from 'ember-ajax/services/ajax';
export default AjaxService.extend({
session: Ember.inject.service(),
headers: Ember.computed("session.authToken", function() {
return {
"API_KEY": Ember.get(document.cookie.match(/apiKey\=([^;]*)/), "1"),
"ANOTHER_HEADER": "Some header value"
};
}).volatile()
});
```
**/
export default Ember.Service.extend({
request(url, options) {
var opts;
if (arguments.length > 2 || typeof options === 'string') {
deprecate(
'ember-ajax/ajax#request calling request with `type` is deprecated and will be removed in ember-ajax@1.0.0. If you want to specify a type pass an object like {type: \'DELETE\'}',
false, { id: 'ember-ajax.service.request' }
);
if (arguments.length > 2) {
opts = arguments[2];
opts.type = options;
} else {
opts = { type: options };
}
} else {
opts = options;
}
const hash = this.options(url, opts);
return new Ember.RSVP.Promise((resolve, reject) => {
hash.success = (payload, textStatus, jqXHR) => {
let response = this.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
payload
);
if (response instanceof AjaxError) {
reject(response);
} else {
resolve(response);
}
};
hash.error = (jqXHR, textStatus, errorThrown) => {
let error;
if (!(error instanceof Error)) {
if (errorThrown instanceof Error) {
error = errorThrown;
} else {
error = this.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
this.parseErrorResponse(jqXHR.responseText) || errorThrown
);
}
}
reject(error);
};
Ember.$.ajax(hash);
}, `ember-ajax: ${hash.type} to ${url}`);
},
/**
@method options
@private
@param {String} url
@param {Object} options
@return {Object}
*/
options(url, options) {
var hash = options || {};
hash.url = url;
hash.type = hash.type || 'GET';
hash.dataType = hash.dataType || 'json';
hash.context = this;
var headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function (xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return hash;
},
/**
Takes an ajax response, and returns the json payload or an error.
By default this hook just returns the json payload passed to it.
You might want to override it in two cases:
1. Your API might return useful results in the response headers.
Response headers are passed in as the second argument.
2. Your API might return errors as successful responses with status code
200 and an Errors text or object.
@method handleResponse
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Object | DS.AdapterError} response
*/
handleResponse(status, headers, payload) {
if (this.isSuccess(status, headers, payload)) {
return payload;
} else if (this.isUnauthorized(status, headers, payload)) {
return new UnauthorizedError(payload.errors);
} else if (this.isForbidden(status, headers, payload)){
return new ForbiddenError(payload.errors);
} else if (this.isInvalid(status, headers, payload)) {
return new InvalidError(payload.errors);
}
let errors = this.normalizeErrorResponse(status, headers, payload);
return new AjaxError(errors);
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is a an authorized error.
@method isUnauthorized
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isUnauthorized(status/*, headers, payload */) {
return status === 401;
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is a forbidden error.
@method isForbidden
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isForbidden(status/*, headers, payload */) {
return status === 403;
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is a an invalid error.
@method isInvalid
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isInvalid(status/*, headers, payload */) {
return status === 422;
},
/**
Default `handleResponse` implementation uses this hook to decide if the
response is a success.
@method isSuccess
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Boolean}
*/
isSuccess(status/*, headers, payload */) {
return status >= 200 && status < 300 || status === 304;
},
/**
@method parseErrorResponse
@private
@param {String} responseText
@return {Object}
*/
parseErrorResponse(responseText) {
var json = responseText;
try {
json = Ember.$.parseJSON(responseText);
} catch (e) {}
return json;
},
/**
@method normalizeErrorResponse
@private
@param {Number} status
@param {Object} headers
@param {Object} payload
@return {Object} errors payload
*/
normalizeErrorResponse(status, headers, payload) {
if (payload && typeof payload === 'object' && payload.errors) {
return payload.errors;
} else {
return [
{
status: `${status}`,
title: "The backend responded with an error",
detail: `${payload}`
}
];
}
}
});