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-request.js
328 lines (299 loc) · 8.42 KB
/
ajax-request.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
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
import Ember from 'ember';
import {
AjaxError,
UnauthorizedError,
InvalidError,
ForbiddenError,
BadRequestError,
NotFoundError,
ServerError,
isUnauthorizedError,
isForbiddenError,
isInvalidError,
isBadRequestError,
isNotFoundError,
isServerError,
isSuccess
} from './errors';
import parseResponseHeaders from './utils/parse-response-headers';
const {
$,
RSVP: { Promise },
get,
isBlank
} = Ember;
export default class AjaxRequest {
request(url, options) {
const hash = this.options(url, options);
return new Promise((resolve, reject) => {
this.raw(url, hash)
.then(({ response }) => {
resolve(response);
})
.catch(({ response }) => {
reject(response);
});
}, `ember-ajax: ${hash.type} ${hash.url} response`);
}
raw(url, options) {
const hash = this.options(url, options);
return new Promise((resolve, reject) => {
hash.success = (payload, textStatus, jqXHR) => {
let response = this.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
payload
);
if (response instanceof AjaxError) {
reject({ payload, textStatus, jqXHR, response });
} else {
resolve({ payload, textStatus, jqXHR, response });
}
};
hash.error = (jqXHR, textStatus, errorThrown) => {
const payload = this.parseErrorResponse(jqXHR.responseText) || errorThrown;
const response = this.handleResponse(
jqXHR.status,
parseResponseHeaders(jqXHR.getAllResponseHeaders()),
payload
);
reject({ payload, textStatus, jqXHR, errorThrown, response });
};
$.ajax(hash);
}, `ember-ajax: ${hash.type} ${hash.url}`);
}
/**
* calls `request()` but forces `options.type` to `POST`
* @public
*/
post(url, options) {
return this.request(url, this._addTypeToOptionsFor(options, 'POST'));
}
/**
* calls `request()` but forces `options.type` to `PUT`
* @public
*/
put(url, options) {
return this.request(url, this._addTypeToOptionsFor(options, 'PUT'));
}
/**
* calls `request()` but forces `options.type` to `PATCH`
* @public
*/
patch(url, options) {
return this.request(url, this._addTypeToOptionsFor(options, 'PATCH'));
}
/**
* calls `request()` but forces `options.type` to `DELETE`
* @public
*/
del(url, options) {
return this.request(url, this._addTypeToOptionsFor(options, 'DELETE'));
}
// forcibly manipulates the options hash to include the HTTP method on the type key
_addTypeToOptionsFor(options, method) {
options = options || {};
options.type = method;
return options;
}
/**
* @method options
* @private
* @param {String} url
* @param {Object} options
* @return {Object}
*/
options(url, options) {
const hash = options || {};
hash.url = this._buildURL(url, hash);
hash.type = hash.type || 'GET';
hash.dataType = hash.dataType || 'json';
hash.context = this;
const headers = get(this, 'headers');
if (headers !== undefined) {
hash.beforeSend = function(xhr) {
Object.keys(headers).forEach((key) => xhr.setRequestHeader(key, headers[key]));
};
}
return hash;
}
_buildURL(url, options) {
const host = options.host || get(this, 'host');
if (isBlank(host) || host === '/') {
return url;
}
const startsWith = String.prototype.startsWith || function(searchString, position) {
position = position || 0;
return this.indexOf(searchString, position) === position;
};
if (startsWith.call(url, '/')) {
return `${host}${url}`;
} else {
return `${host}/${url}`;
}
}
/**
* 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
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Object | DS.AdapterError} response
*/
handleResponse(status, headers, payload) {
payload = payload || {};
if (this.isSuccess(status, headers, payload)) {
return payload;
} else if (this.isUnauthorizedError(status, headers, payload)) {
return new UnauthorizedError(payload.errors);
} else if (this.isForbiddenError(status, headers, payload)) {
return new ForbiddenError(payload.errors);
} else if (this.isInvalidError(status, headers, payload)) {
return new InvalidError(payload.errors);
} else if (this.isBadRequestError(status, headers, payload)) {
return new BadRequestError(payload.errors);
} else if (this.isNotFoundError(status, headers, payload)) {
return new NotFoundError(payload.errors);
} else if (this.isServerError(status, headers, payload)) {
return new ServerError(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 isUnauthorizedError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isUnauthorizedError(status) {
return isUnauthorizedError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a forbidden error.
* @method isForbiddenError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isForbiddenError(status) {
return isForbiddenError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a an invalid error.
* @method isInvalidError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isInvalidError(status) {
return isInvalidError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a bad request error.
* @method isBadRequestError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isBadRequestError(status) {
return isBadRequestError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a "not found" error.
* @method isNotFoundError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isNotFoundError(status) {
return isNotFoundError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a server error.
* @method isServerError
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isServerError(status) {
return isServerError(status);
}
/**
* Default `handleResponse` implementation uses this hook to decide if the
* response is a success.
* @method isSuccess
* @private
* @param {Number} status
* @param {Object} headers
* @param {Object} payload
* @return {Boolean}
*/
isSuccess(status) {
return isSuccess(status);
}
/**
* @method parseErrorResponse
* @private
* @param {String} responseText
* @return {Object}
*/
parseErrorResponse(responseText) {
let 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
}
];
}
}
}