-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
432 lines (380 loc) · 13.4 KB
/
index.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
/**
* yea
*
* @license MIT
* @author Martti Laine <[email protected]>
* @link https://github.com/codeclown/yea
*/
(function (factory) {
if(typeof exports === 'object' && typeof module === 'object') {
module.exports = factory();
} else if(typeof define === 'function' && define.amd) {
define(factory);
} else {
window['yea'] = factory();
}
})(function () {
function assign(target) {
var to = Object(target);
for (var index = 1; index < arguments.length; index++) {
var nextSource = arguments[index];
if (nextSource !== null && nextSource !== undefined) {
for (var nextKey in nextSource) {
if (typeof nextSource[nextKey] !== 'undefined') {
to[nextKey] = nextSource[nextKey];
}
}
}
}
return to;
}
function toQueryString(data) {
var segments = [];
for (var key in data) {
var value = data[key];
if (Array.isArray(value)) {
for (var i in value) {
if (typeof value[i] !== 'undefined') {
if (value[i] === null) {
segments.push(encodeURIComponent(key));
} else {
segments.push(encodeURIComponent(key) + '=' + encodeURIComponent(value[i]));
}
}
}
} else {
if (typeof value !== 'undefined') {
if (value === null) {
segments.push(encodeURIComponent(key));
} else {
segments.push(encodeURIComponent(key) + '=' + encodeURIComponent(value));
}
}
}
}
return segments.join('&');
}
function replaceUrlParams(url, params) {
for (var key in params) {
var regex = new RegExp(':' + key, 'g');
url = url.replace(regex, params[key]);
}
return url;
}
function createUrl(baseUrl, path, query) {
var url = '';
if (baseUrl) {
url += baseUrl.replace(/\/*$/, '');
if (path.length && path[0] !== '/') {
url += '/';
}
}
url += path;
if (query) {
url += '?' + query;
}
return url;
}
function mergeConfig(config, updated) {
return assign({}, config, updated, {
urlParams: assign({}, config.urlParams, updated.urlParams || {}),
headers: assign({}, config.headers, updated.headers || {}),
responseTransformers: [].concat(updated.responseTransformers || config.responseTransformers),
polyfills: assign({}, config.polyfills, updated.polyfills || {}),
prop: [].concat(updated.prop || config.prop),
});
}
function jsonResponseTransformer(response) {
if (response.headers['content-type'] && response.headers['content-type'].indexOf('application/json') === 0) {
response.data = JSON.parse(response.body);
}
return response;
}
function parsePropPath(path) {
if (Array.isArray(path)) {
return path;
}
return path.replace(/\]$/, '').replace(/[[\]]/g, '.').split('.');
}
function applyPropPath(object, path) {
var value = object;
for (var i = 0; i < path.length; i++) {
value = value[path[i]];
}
return value;
}
function YeaAjaxRequest(config) {
this._config = config;
this.jsonResponseTransformer = jsonResponseTransformer;
// The .utils API is not guaranteed to be stable.
// Exposed only for testing purposes.
this.utils = {
assign: assign,
toQueryString: toQueryString,
replaceUrlParams: replaceUrlParams,
createUrl: createUrl,
parsePropPath: parsePropPath,
applyPropPath: applyPropPath
};
}
YeaAjaxRequest.prototype.method = function method(method) {
method = method.toUpperCase();
if (['GET', 'POST', 'PUT', 'DELETE'].indexOf(method) === -1) {
throw new Error('Invalid method: \'' + method + '\'');
}
return new YeaAjaxRequest(mergeConfig(this._config, { method: method }));
};
YeaAjaxRequest.prototype.get = function get(url) {
return this.method('get').url(url);
};
YeaAjaxRequest.prototype.post = function post(url) {
return this.method('post').url(url);
};
YeaAjaxRequest.prototype.put = function put(url) {
return this.method('put').url(url);
};
YeaAjaxRequest.prototype['delete'] = function yeaDelete(url) {
return this.method('delete').url(url);
};
YeaAjaxRequest.prototype.url = function url(fullUrl) {
var segments = fullUrl.split('?');
var url = segments[0];
var query = segments[1] || '';
return new YeaAjaxRequest(mergeConfig(this._config, { url: url, query: query }));
};
YeaAjaxRequest.prototype.urlParams = function urlParams(urlParams) {
var config = mergeConfig(this._config, {});
config.urlParams = assign({}, urlParams);
return new YeaAjaxRequest(config);
};
YeaAjaxRequest.prototype.baseUrl = function baseUrl(baseUrl) {
if (baseUrl === null) {
baseUrl = '';
}
return new YeaAjaxRequest(mergeConfig(this._config, { baseUrl: baseUrl }));
};
YeaAjaxRequest.prototype.query = function query(query) {
if (typeof query !== 'string') {
query = toQueryString(query);
}
return new YeaAjaxRequest(mergeConfig(this._config, { query: query }));
};
YeaAjaxRequest.prototype.headers = function headers(object) {
var headers = {};
for (var name in object) {
var value = object[name];
name = name.toLowerCase();
if (typeof value === 'string') {
headers[name] = value;
} else if (typeof value === 'number') {
headers[name] = value.toString();
} else {
throw new Error('Invalid header value for header \'' + name + '\'');
}
}
var config = mergeConfig(this._config, {});
config.headers = headers;
return new YeaAjaxRequest(config);
};
YeaAjaxRequest.prototype.amendHeaders = function amendHeaders(object) {
var headers = assign({}, this._config.headers);
for (var name in object) {
var value = object[name];
name = name.toLowerCase();
if (typeof value === 'string') {
headers[name] = value;
} else if (typeof value === 'number') {
headers[name] = value.toString();
} else {
throw new Error('Invalid header value for header \'' + name + '\'');
}
}
return new YeaAjaxRequest(mergeConfig(this._config, { headers: headers }));
};
YeaAjaxRequest.prototype.body = function body(data) {
if (typeof data === 'number') {
data = data.toString();
} else if (typeof data !== 'string') {
throw new Error('Unexpected type for request body');
}
return new YeaAjaxRequest(mergeConfig(this._config, { body: data }));
};
YeaAjaxRequest.prototype.urlencoded = function urlencoded(data) {
return this.header('content-type', 'application/x-www-form-urlencoded').body(toQueryString(data));
};
YeaAjaxRequest.prototype.json = function json(data) {
return this.header('content-type', 'application/json').body(JSON.stringify(data));
};
YeaAjaxRequest.prototype.header = function header(name, value) {
var config = mergeConfig(this._config, {});
config.headers[name.toLowerCase()] = value;
return new YeaAjaxRequest(config);
};
YeaAjaxRequest.prototype.unsetHeader = function unsetHeader(name) {
var config = mergeConfig(this._config, {});
name = name.toLowerCase();
if (typeof config.headers[name] !== 'undefined') {
delete config.headers[name];
}
return new YeaAjaxRequest(config);
};
YeaAjaxRequest.prototype.timeout = function timeout(milliseconds) {
if (milliseconds === null || milliseconds === 0) {
milliseconds = null;
} else if (typeof milliseconds !== 'number') {
throw new Error('Expected a number for timeout');
}
return new YeaAjaxRequest(mergeConfig(this._config, { timeout: milliseconds }));
};
YeaAjaxRequest.prototype.unsetTimeout = function unsetTimeout() {
return new YeaAjaxRequest(mergeConfig(this._config, { timeout: null }));
};
YeaAjaxRequest.prototype.prop = function prop(path) {
if (path === null || path === '') {
path = [];
} else if (typeof path === 'string') {
path = parsePropPath(path);
} else if (!Array.isArray(path)) {
throw new Error('Expected a string (e.g. "data.items[0]") or an array for prop');
}
return new YeaAjaxRequest(mergeConfig(this._config, { prop: path }));
};
YeaAjaxRequest.prototype.setResponseTransformers = function setResponseTransformers(transformers) {
if (!Array.isArray(transformers)) {
throw new Error('Expected an array of response transformers');
}
for (var i in transformers) {
if (typeof transformers[i] !== 'function') {
throw new Error('One or more response transformer is not a function');
}
}
return new YeaAjaxRequest(mergeConfig(this._config, { responseTransformers: transformers }));
};
YeaAjaxRequest.prototype.setAllowedStatusCode = function setAllowedStatusCode(allowedStatusCode) {
if (typeof allowedStatusCode !== 'number' && !(allowedStatusCode instanceof RegExp) && typeof allowedStatusCode !== 'function') {
throw new Error('Expected a number, a regex or a function in setAllowedStatusCode');
}
return new YeaAjaxRequest(mergeConfig(this._config, { allowedStatusCode: allowedStatusCode }));
};
YeaAjaxRequest.prototype.polyfills = function polyfills(polyfills) {
var config = mergeConfig(this._config, { polyfills: polyfills });
if (polyfills === null) {
config.polyfills = {};
}
return new YeaAjaxRequest(config);
};
YeaAjaxRequest.prototype.toObject = function toObject() {
return mergeConfig(this._config, {});
};
YeaAjaxRequest.prototype.config = function config() {
return this.toObject();
};
YeaAjaxRequest.prototype.debug = function debug() {
return this.toObject();
};
YeaAjaxRequest.prototype.sendUrlencoded = function sendUrlencoded(data) {
return this.urlencoded(data).send();
};
YeaAjaxRequest.prototype.sendJson = function sendJson(data) {
return this.json(data).send();
};
YeaAjaxRequest.prototype.then = function then() {
var args = arguments;
var promise = this.send();
return promise.then.apply(promise, args);
};
YeaAjaxRequest.prototype.send = function send(body) {
var config = this._config;
var timeoutId;
var didTimeout = false;
var PromiseImplementation = config.polyfills.Promise || window.Promise;
return new PromiseImplementation(function sendPromise(resolve, reject) {
var httpRequest = new XMLHttpRequest();
httpRequest.onreadystatechange = function onreadystatechange() {
try {
if (httpRequest.readyState === XMLHttpRequest.DONE && !didTimeout) {
var headers = {};
var items = httpRequest.getAllResponseHeaders().split('\r\n');
for (var i = 0; i < items.length; i++) {
if (!items[i]) {
continue;
}
var segments = items[i].split(': ');
// TODO: missing test, search for 'lowercases incoming response header names'
var key = segments[0].toLowerCase();
headers[key] = segments[1];
}
var response = {
headers: headers,
status: httpRequest.status,
body: httpRequest.responseText
};
var isValid;
if (typeof config.allowedStatusCode === 'number') {
isValid = response.status === config.allowedStatusCode;
} else if (config.allowedStatusCode instanceof RegExp) {
isValid = config.allowedStatusCode.test(response.status);
} else if (typeof config.allowedStatusCode === 'function') {
isValid = config.allowedStatusCode(response.status);
}
var transformers = config.responseTransformers.concat();
var transformer;
// eslint-disable-next-line no-cond-assign
while (transformer = transformers.shift()) {
response = transformer(response);
}
if (isValid) {
if (timeoutId) {
clearTimeout(timeoutId);
}
response = applyPropPath(response, config.prop);
resolve(response);
} else {
var error = new Error('Request failed with status ' + response.status);
error.response = response;
reject(error);
}
}
} catch (exception) {
reject(exception);
}
};
var url = replaceUrlParams(config.url, config.urlParams);
var fullUrl = createUrl(config.baseUrl, url, config.query);
httpRequest.open(config.method, fullUrl, true);
for (var name in config.headers) {
httpRequest.setRequestHeader(name, config.headers[name]);
}
if (config.timeout !== null) {
timeoutId = setTimeout(function () {
reject(new Error('Request failed due to timeout (' + config.timeout + 'ms)'));
didTimeout = true;
httpRequest.abort();
}, config.timeout);
}
if (config.method === 'get') {
httpRequest.send();
} else {
httpRequest.send(typeof body !== 'undefined' ? body : config.body);
}
});
};
// Export a new instance from which all new requests are to be extended
var baseRequest = new YeaAjaxRequest({
method: 'GET',
baseUrl: '',
url: '',
urlParams: {},
query: '',
body: '',
headers: {},
allowedStatusCode: /^2[0-9]{2}$/,
timeout: null,
prop: [],
responseTransformers: [
jsonResponseTransformer
],
polyfills: {}
});
return baseRequest;
});