-
Notifications
You must be signed in to change notification settings - Fork 1.3k
/
request-base.js
778 lines (681 loc) · 18 KB
/
request-base.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
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
/**
* Module of mixed-in functions shared between node and client code
*/
const { isObject, hasOwn } = require('./utils');
/**
* Expose `RequestBase`.
*/
module.exports = RequestBase;
/**
* Initialize a new `RequestBase`.
*
* @api public
*/
function RequestBase() {}
/**
* Clear previous timeout.
*
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.clearTimeout = function () {
clearTimeout(this._timer);
clearTimeout(this._responseTimeoutTimer);
clearTimeout(this._uploadTimeoutTimer);
delete this._timer;
delete this._responseTimeoutTimer;
delete this._uploadTimeoutTimer;
return this;
};
/**
* Override default response body parser
*
* This function will be called to convert incoming data into request.body
*
* @param {Function}
* @api public
*/
RequestBase.prototype.parse = function (fn) {
this._parser = fn;
return this;
};
/**
* Set format of binary response body.
* In browser valid formats are 'blob' and 'arraybuffer',
* which return Blob and ArrayBuffer, respectively.
*
* In Node all values result in Buffer.
*
* Examples:
*
* req.get('/')
* .responseType('blob')
* .end(callback);
*
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.responseType = function (value) {
this._responseType = value;
return this;
};
/**
* Override default request body serializer
*
* This function will be called to convert data set via .send or .attach into payload to send
*
* @param {Function}
* @api public
*/
RequestBase.prototype.serialize = function (fn) {
this._serializer = fn;
return this;
};
/**
* Set timeouts.
*
* - response timeout is time between sending request and receiving the first byte of the response. Includes DNS and connection time.
* - deadline is the time from start of the request to receiving response body in full. If the deadline is too short large files may not load at all on slow connections.
* - upload is the time since last bit of data was sent or received. This timeout works only if deadline timeout is off
*
* Value of 0 or false means no timeout.
*
* @param {Number|Object} ms or {response, deadline}
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.timeout = function (options) {
if (!options || typeof options !== 'object') {
this._timeout = options;
this._responseTimeout = 0;
this._uploadTimeout = 0;
return this;
}
for (const option in options) {
if (hasOwn(options, option)) {
switch (option) {
case 'deadline':
this._timeout = options.deadline;
break;
case 'response':
this._responseTimeout = options.response;
break;
case 'upload':
this._uploadTimeout = options.upload;
break;
default:
console.warn('Unknown timeout option', option);
}
}
}
return this;
};
/**
* Set number of retry attempts on error.
*
* Failed requests will be retried 'count' times if timeout or err.code >= 500.
*
* @param {Number} count
* @param {Function} [fn]
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.retry = function (count, fn) {
// Default to 1 if no count passed or true
if (arguments.length === 0 || count === true) count = 1;
if (count <= 0) count = 0;
this._maxRetries = count;
this._retries = 0;
this._retryCallback = fn;
return this;
};
//
// NOTE: we do not include ESOCKETTIMEDOUT because that is from `request` package
// <https://github.com/sindresorhus/got/pull/537>
//
// NOTE: we do not include EADDRINFO because it was removed from libuv in 2014
// <https://github.com/libuv/libuv/commit/02e1ebd40b807be5af46343ea873331b2ee4e9c1>
// <https://github.com/request/request/search?q=ESOCKETTIMEDOUT&unscoped_q=ESOCKETTIMEDOUT>
//
//
// TODO: expose these as configurable defaults
//
const ERROR_CODES = new Set([
'ETIMEDOUT',
'ECONNRESET',
'EADDRINUSE',
'ECONNREFUSED',
'EPIPE',
'ENOTFOUND',
'ENETUNREACH',
'EAI_AGAIN'
]);
const STATUS_CODES = new Set([
408, 413, 429, 500, 502, 503, 504, 521, 522, 524
]);
// TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
// const METHODS = new Set(['GET', 'PUT', 'HEAD', 'DELETE', 'OPTIONS', 'TRACE']);
/**
* Determine if a request should be retried.
* (Inspired by https://github.com/sindresorhus/got#retry)
*
* @param {Error} err an error
* @param {Response} [res] response
* @returns {Boolean} if segment should be retried
*/
RequestBase.prototype._shouldRetry = function (error, res) {
if (!this._maxRetries || this._retries++ >= this._maxRetries) {
return false;
}
if (this._retryCallback) {
try {
const override = this._retryCallback(error, res);
if (override === true) return true;
if (override === false) return false;
// undefined falls back to defaults
} catch (err) {
console.error(err);
}
}
// TODO: we would need to make this easily configurable before adding it in (e.g. some might want to add POST)
/*
if (
this.req &&
this.req.method &&
!METHODS.has(this.req.method.toUpperCase())
)
return false;
*/
if (res && res.status && STATUS_CODES.has(res.status)) return true;
if (error) {
if (error.code && ERROR_CODES.has(error.code)) return true;
// Superagent timeout
if (error.timeout && error.code === 'ECONNABORTED') return true;
if (error.crossDomain) return true;
}
return false;
};
/**
* Retry request
*
* @return {Request} for chaining
* @api private
*/
RequestBase.prototype._retry = function () {
this.clearTimeout();
// node
if (this.req) {
this.req = null;
this.req = this.request();
}
this._aborted = false;
this.timedout = false;
this.timedoutError = null;
return this._end();
};
/**
* Promise support
*
* @param {Function} resolve
* @param {Function} [reject]
* @return {Request}
*/
RequestBase.prototype.then = function (resolve, reject) {
if (!this._fullfilledPromise) {
const self = this;
if (this._endCalled) {
console.warn(
'Warning: superagent request was sent twice, because both .end() and .then() were called. Never call .end() if you use promises'
);
}
this._fullfilledPromise = new Promise((resolve, reject) => {
self.on('abort', () => {
if (this._maxRetries && this._maxRetries > this._retries) {
return;
}
if (this.timedout && this.timedoutError) {
reject(this.timedoutError);
return;
}
const error = new Error('Aborted');
error.code = 'ABORTED';
error.status = this.status;
error.method = this.method;
error.url = this.url;
reject(error);
});
self.end((error, res) => {
if (error) reject(error);
else resolve(res);
});
});
}
return this._fullfilledPromise.then(resolve, reject);
};
RequestBase.prototype.catch = function (callback) {
return this.then(undefined, callback);
};
/**
* Allow for extension
*/
RequestBase.prototype.use = function (fn) {
fn(this);
return this;
};
RequestBase.prototype.ok = function (callback) {
if (typeof callback !== 'function') throw new Error('Callback required');
this._okCallback = callback;
return this;
};
RequestBase.prototype._isResponseOK = function (res) {
if (!res) {
return false;
}
if (this._okCallback) {
return this._okCallback(res);
}
return res.status >= 200 && res.status < 300;
};
/**
* Get request header `field`.
* Case-insensitive.
*
* @param {String} field
* @return {String}
* @api public
*/
RequestBase.prototype.get = function (field) {
return this._header[field.toLowerCase()];
};
/**
* Get case-insensitive header `field` value.
* This is a deprecated internal API. Use `.get(field)` instead.
*
* (getHeader is no longer used internally by the superagent code base)
*
* @param {String} field
* @return {String}
* @api private
* @deprecated
*/
RequestBase.prototype.getHeader = RequestBase.prototype.get;
/**
* Set header `field` to `val`, or multiple fields with one object.
* Case-insensitive.
*
* Examples:
*
* req.get('/')
* .set('Accept', 'application/json')
* .set('X-API-Key', 'foobar')
* .end(callback);
*
* req.get('/')
* .set({ Accept: 'application/json', 'X-API-Key': 'foobar' })
* .end(callback);
*
* @param {String|Object} field
* @param {String} val
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.set = function (field, value) {
if (isObject(field)) {
for (const key in field) {
if (hasOwn(field, key)) this.set(key, field[key]);
}
return this;
}
this._header[field.toLowerCase()] = value;
this.header[field] = value;
return this;
};
/**
* Remove header `field`.
* Case-insensitive.
*
* Example:
*
* req.get('/')
* .unset('User-Agent')
* .end(callback);
*
* @param {String} field field name
*/
RequestBase.prototype.unset = function (field) {
delete this._header[field.toLowerCase()];
delete this.header[field];
return this;
};
/**
* Write the field `name` and `val`, or multiple fields with one object
* for "multipart/form-data" request bodies.
*
* ``` js
* request.post('/upload')
* .field('foo', 'bar')
* .end(callback);
*
* request.post('/upload')
* .field({ foo: 'bar', baz: 'qux' })
* .end(callback);
* ```
*
* @param {String|Object} name name of field
* @param {String|Blob|File|Buffer|fs.ReadStream} val value of field
* @param {String} options extra options, e.g. 'blob'
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.field = function (name, value, options) {
// name should be either a string or an object.
if (name === null || undefined === name) {
throw new Error('.field(name, val) name can not be empty');
}
if (this._data) {
throw new Error(
".field() can't be used if .send() is used. Please use only .send() or only .field() & .attach()"
);
}
if (isObject(name)) {
for (const key in name) {
if (hasOwn(name, key)) this.field(key, name[key]);
}
return this;
}
if (Array.isArray(value)) {
for (const i in value) {
if (hasOwn(value, i)) this.field(name, value[i]);
}
return this;
}
// val should be defined now
if (value === null || undefined === value) {
throw new Error('.field(name, val) val can not be empty');
}
if (typeof value === 'boolean') {
value = String(value);
}
// fix https://github.com/ladjs/superagent/issues/1680
if (options) this._getFormData().append(name, value, options);
else this._getFormData().append(name, value);
return this;
};
/**
* Abort the request, and clear potential timeout.
*
* @return {Request} request
* @api public
*/
RequestBase.prototype.abort = function () {
if (this._aborted) {
return this;
}
this._aborted = true;
if (this.xhr) this.xhr.abort(); // browser
if (this.req) {
this.req.abort(); // node
}
this.clearTimeout();
this.emit('abort');
return this;
};
RequestBase.prototype._auth = function (user, pass, options, base64Encoder) {
switch (options.type) {
case 'basic':
this.set('Authorization', `Basic ${base64Encoder(`${user}:${pass}`)}`);
break;
case 'auto':
this.username = user;
this.password = pass;
break;
case 'bearer': // usage would be .auth(accessToken, { type: 'bearer' })
this.set('Authorization', `Bearer ${user}`);
break;
default:
break;
}
return this;
};
/**
* Enable transmission of cookies with x-domain requests.
*
* Note that for this to work the origin must not be
* using "Access-Control-Allow-Origin" with a wildcard,
* and also must set "Access-Control-Allow-Credentials"
* to "true".
* @param {Boolean} [on=true] - Set 'withCredentials' state
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.withCredentials = function (on) {
// This is browser-only functionality. Node side is no-op.
if (on === undefined) on = true;
this._withCredentials = on;
return this;
};
/**
* Set the max redirects to `n`. Does nothing in browser XHR implementation.
*
* @param {Number} n
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.redirects = function (n) {
this._maxRedirects = n;
return this;
};
/**
* Maximum size of buffered response body, in bytes. Counts uncompressed size.
* Default 200MB.
*
* @param {Number} n number of bytes
* @return {Request} for chaining
*/
RequestBase.prototype.maxResponseSize = function (n) {
if (typeof n !== 'number') {
throw new TypeError('Invalid argument');
}
this._maxResponseSize = n;
return this;
};
/**
* Convert to a plain javascript object (not JSON string) of scalar properties.
* Note as this method is designed to return a useful non-this value,
* it cannot be chained.
*
* @return {Object} describing method, url, and data of this request
* @api public
*/
RequestBase.prototype.toJSON = function () {
return {
method: this.method,
url: this.url,
data: this._data,
headers: this._header
};
};
/**
* Send `data` as the request body, defaulting the `.type()` to "json" when
* an object is given.
*
* Examples:
*
* // manual json
* request.post('/user')
* .type('json')
* .send('{"name":"tj"}')
* .end(callback)
*
* // auto json
* request.post('/user')
* .send({ name: 'tj' })
* .end(callback)
*
* // manual x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send('name=tj')
* .end(callback)
*
* // auto x-www-form-urlencoded
* request.post('/user')
* .type('form')
* .send({ name: 'tj' })
* .end(callback)
*
* // defaults to x-www-form-urlencoded
* request.post('/user')
* .send('name=tobi')
* .send('species=ferret')
* .end(callback)
*
* @param {String|Object} data
* @return {Request} for chaining
* @api public
*/
// eslint-disable-next-line complexity
RequestBase.prototype.send = function (data) {
const isObject_ = isObject(data);
let type = this._header['content-type'];
if (this._formData) {
throw new Error(
".send() can't be used if .attach() or .field() is used. Please use only .send() or only .field() & .attach()"
);
}
if (isObject_ && !this._data) {
if (Array.isArray(data)) {
this._data = [];
} else if (!this._isHost(data)) {
this._data = {};
}
} else if (data && this._data && this._isHost(this._data)) {
throw new Error("Can't merge these send calls");
}
// merge
if (isObject_ && isObject(this._data)) {
for (const key in data) {
if (typeof data[key] == 'bigint' && !data[key].toJSON)
throw new Error('Cannot serialize BigInt value to json');
if (hasOwn(data, key)) this._data[key] = data[key];
}
}
else if (typeof data === 'bigint') throw new Error("Cannot send value of type BigInt");
else if (typeof data === 'string') {
// default to x-www-form-urlencoded
if (!type) this.type('form');
type = this._header['content-type'];
if (type) type = type.toLowerCase().trim();
if (type === 'application/x-www-form-urlencoded') {
this._data = this._data ? `${this._data}&${data}` : data;
} else {
this._data = (this._data || '') + data;
}
} else {
this._data = data;
}
if (!isObject_ || this._isHost(data)) {
return this;
}
// default to json
if (!type) this.type('json');
return this;
};
/**
* Sort `querystring` by the sort function
*
*
* Examples:
*
* // default order
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery()
* .end(callback)
*
* // customized sort function
* request.get('/user')
* .query('name=Nick')
* .query('search=Manny')
* .sortQuery(function(a, b){
* return a.length - b.length;
* })
* .end(callback)
*
*
* @param {Function} sort
* @return {Request} for chaining
* @api public
*/
RequestBase.prototype.sortQuery = function (sort) {
// _sort default to true but otherwise can be a function or boolean
this._sort = typeof sort === 'undefined' ? true : sort;
return this;
};
/**
* Compose querystring to append to req.url
*
* @api private
*/
RequestBase.prototype._finalizeQueryString = function () {
const query = this._query.join('&');
if (query) {
this.url += (this.url.includes('?') ? '&' : '?') + query;
}
this._query.length = 0; // Makes the call idempotent
if (this._sort) {
const index = this.url.indexOf('?');
if (index >= 0) {
const queryArray = this.url.slice(index + 1).split('&');
if (typeof this._sort === 'function') {
queryArray.sort(this._sort);
} else {
queryArray.sort();
}
this.url = this.url.slice(0, index) + '?' + queryArray.join('&');
}
}
};
// For backwards compat only
RequestBase.prototype._appendQueryString = () => {
console.warn('Unsupported');
};
/**
* Invoke callback with timeout error.
*
* @api private
*/
RequestBase.prototype._timeoutError = function (reason, timeout, errno) {
if (this._aborted) {
return;
}
const error = new Error(`${reason + timeout}ms exceeded`);
error.timeout = timeout;
error.code = 'ECONNABORTED';
error.errno = errno;
this.timedout = true;
this.timedoutError = error;
this.abort();
this.callback(error);
};
RequestBase.prototype._setTimeouts = function () {
const self = this;
// deadline
if (this._timeout && !this._timer) {
this._timer = setTimeout(() => {
self._timeoutError('Timeout of ', self._timeout, 'ETIME');
}, this._timeout);
}
// response timeout
if (this._responseTimeout && !this._responseTimeoutTimer) {
this._responseTimeoutTimer = setTimeout(() => {
self._timeoutError(
'Response timeout of ',
self._responseTimeout,
'ETIMEDOUT'
);
}, this._responseTimeout);
}
};