got 11.5.2 → 11.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/source/as-promise/index.d.ts +1 -3
- package/dist/source/as-promise/index.js +44 -125
- package/dist/source/as-promise/normalize-arguments.d.ts +3 -0
- package/dist/source/as-promise/normalize-arguments.js +78 -0
- package/dist/source/as-promise/parse-body.d.ts +3 -0
- package/dist/source/as-promise/parse-body.js +25 -0
- package/dist/source/as-promise/types.d.ts +206 -24
- package/dist/source/as-promise/types.js +18 -7
- package/dist/source/{as-promise → core}/calculate-retry-delay.d.ts +2 -1
- package/dist/source/core/calculate-retry-delay.js +29 -0
- package/dist/source/core/index.d.ts +822 -5
- package/dist/source/core/index.js +198 -39
- package/dist/source/core/utils/is-response-ok.d.ts +2 -0
- package/dist/source/core/utils/is-response-ok.js +8 -0
- package/dist/source/create.js +16 -7
- package/dist/source/index.js +3 -2
- package/dist/source/types.d.ts +240 -1
- package/package.json +20 -16
- package/readme.md +75 -7
- package/dist/source/as-promise/calculate-retry-delay.js +0 -38
- package/dist/source/as-promise/core.d.ts +0 -13
- package/dist/source/as-promise/core.js +0 -127
package/dist/source/types.d.ts
CHANGED
|
@@ -1,20 +1,62 @@
|
|
|
1
1
|
/// <reference types="node" />
|
|
2
2
|
import { URL } from 'url';
|
|
3
3
|
import { CancelError } from 'p-cancelable';
|
|
4
|
-
import { CancelableRequest, Response, Options, NormalizedOptions, Defaults as DefaultOptions, PaginationOptions, ParseError, RequestError, CacheError, ReadError, HTTPError, MaxRedirectsError, TimeoutError } from './as-promise';
|
|
4
|
+
import { CancelableRequest, Response, Options, NormalizedOptions, Defaults as DefaultOptions, PaginationOptions, ParseError, RequestError, CacheError, ReadError, HTTPError, MaxRedirectsError, TimeoutError, UnsupportedProtocolError, UploadError } from './as-promise';
|
|
5
5
|
import Request from './core';
|
|
6
6
|
declare type Except<ObjectType, KeysType extends keyof ObjectType> = Pick<ObjectType, Exclude<keyof ObjectType, KeysType>>;
|
|
7
7
|
declare type Merge<FirstType, SecondType> = Except<FirstType, Extract<keyof FirstType, keyof SecondType>> & SecondType;
|
|
8
|
+
/**
|
|
9
|
+
Defaults for each Got instance.
|
|
10
|
+
*/
|
|
8
11
|
export interface InstanceDefaults {
|
|
12
|
+
/**
|
|
13
|
+
An object containing the default options of Got.
|
|
14
|
+
*/
|
|
9
15
|
options: DefaultOptions;
|
|
16
|
+
/**
|
|
17
|
+
An array of functions. You execute them directly by calling `got()`.
|
|
18
|
+
They are some sort of "global hooks" - these functions are called first.
|
|
19
|
+
The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
|
|
20
|
+
|
|
21
|
+
@default []
|
|
22
|
+
*/
|
|
10
23
|
handlers: HandlerFunction[];
|
|
24
|
+
/**
|
|
25
|
+
A read-only boolean describing whether the defaults are mutable or not.
|
|
26
|
+
If set to `true`, you can update headers over time, for example, update an access token when it expires.
|
|
27
|
+
|
|
28
|
+
@default false
|
|
29
|
+
*/
|
|
11
30
|
mutableDefaults: boolean;
|
|
12
31
|
_rawHandlers?: HandlerFunction[];
|
|
13
32
|
}
|
|
33
|
+
/**
|
|
34
|
+
A Request object returned by calling Got, or any of the Got HTTP alias request functions.
|
|
35
|
+
*/
|
|
14
36
|
export declare type GotReturn = Request | CancelableRequest;
|
|
37
|
+
/**
|
|
38
|
+
A function to handle options and returns a Request object.
|
|
39
|
+
It acts sort of like a "global hook", and will be called before any actual request is made.
|
|
40
|
+
*/
|
|
15
41
|
export declare type HandlerFunction = <T extends GotReturn>(options: NormalizedOptions, next: (options: NormalizedOptions) => T) => T | Promise<T>;
|
|
42
|
+
/**
|
|
43
|
+
The options available for `got.extend()`.
|
|
44
|
+
*/
|
|
16
45
|
export interface ExtendOptions extends Options {
|
|
46
|
+
/**
|
|
47
|
+
An array of functions. You execute them directly by calling `got()`.
|
|
48
|
+
They are some sort of "global hooks" - these functions are called first.
|
|
49
|
+
The last handler (*it's hidden*) is either `asPromise` or `asStream`, depending on the `options.isStream` property.
|
|
50
|
+
|
|
51
|
+
@default []
|
|
52
|
+
*/
|
|
17
53
|
handlers?: HandlerFunction[];
|
|
54
|
+
/**
|
|
55
|
+
A read-only boolean describing whether the defaults are mutable or not.
|
|
56
|
+
If set to `true`, you can update headers over time, for example, update an access token when it expires.
|
|
57
|
+
|
|
58
|
+
@default false
|
|
59
|
+
*/
|
|
18
60
|
mutableDefaults?: boolean;
|
|
19
61
|
}
|
|
20
62
|
export declare type OptionsOfTextResponseBody = Merge<Options, {
|
|
@@ -44,10 +86,60 @@ declare type ResponseBodyOnly = {
|
|
|
44
86
|
resolveBodyOnly: true;
|
|
45
87
|
};
|
|
46
88
|
export declare type OptionsWithPagination<T = unknown, R = unknown> = Merge<Options, PaginationOptions<T, R>>;
|
|
89
|
+
/**
|
|
90
|
+
An instance of `got.paginate`.
|
|
91
|
+
*/
|
|
47
92
|
export interface GotPaginate {
|
|
93
|
+
/**
|
|
94
|
+
Returns an async iterator.
|
|
95
|
+
|
|
96
|
+
See pagination.options for more pagination options.
|
|
97
|
+
|
|
98
|
+
@example
|
|
99
|
+
```
|
|
100
|
+
(async () => {
|
|
101
|
+
const countLimit = 10;
|
|
102
|
+
|
|
103
|
+
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
|
|
104
|
+
pagination: {countLimit}
|
|
105
|
+
});
|
|
106
|
+
|
|
107
|
+
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
|
108
|
+
|
|
109
|
+
for await (const commitData of pagination) {
|
|
110
|
+
console.log(commitData.commit.message);
|
|
111
|
+
}
|
|
112
|
+
})();
|
|
113
|
+
```
|
|
114
|
+
*/
|
|
48
115
|
each: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => AsyncIterableIterator<T>);
|
|
116
|
+
/**
|
|
117
|
+
Returns a Promise for an array of all results.
|
|
118
|
+
|
|
119
|
+
See pagination.options for more pagination options.
|
|
120
|
+
|
|
121
|
+
@example
|
|
122
|
+
```
|
|
123
|
+
(async () => {
|
|
124
|
+
const countLimit = 10;
|
|
125
|
+
|
|
126
|
+
const results = await got.paginate.all('https://api.github.com/repos/sindresorhus/got/commits', {
|
|
127
|
+
pagination: {countLimit}
|
|
128
|
+
});
|
|
129
|
+
|
|
130
|
+
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
|
131
|
+
console.log(results);
|
|
132
|
+
})();
|
|
133
|
+
```
|
|
134
|
+
*/
|
|
49
135
|
all: (<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>) => Promise<T[]>) & (<T, R = unknown>(options?: OptionsWithPagination<T, R>) => Promise<T[]>);
|
|
136
|
+
/**
|
|
137
|
+
Same as `GotPaginate.each`.
|
|
138
|
+
*/
|
|
50
139
|
<T, R = unknown>(url: string | URL, options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
|
|
140
|
+
/**
|
|
141
|
+
Same as `GotPaginate.each`.
|
|
142
|
+
*/
|
|
51
143
|
<T, R = unknown>(options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T>;
|
|
52
144
|
}
|
|
53
145
|
export interface GotRequestFunction {
|
|
@@ -74,6 +166,9 @@ export interface GotRequestFunction {
|
|
|
74
166
|
(url: string | URL, options?: Options): CancelableRequest | Request;
|
|
75
167
|
(options: Options): CancelableRequest | Request;
|
|
76
168
|
}
|
|
169
|
+
/**
|
|
170
|
+
All available HTTP request methods provided by Got.
|
|
171
|
+
*/
|
|
77
172
|
export declare type HTTPAlias = 'get' | 'post' | 'put' | 'patch' | 'head' | 'delete';
|
|
78
173
|
interface GotStreamFunction {
|
|
79
174
|
(url: string | URL, options?: Merge<Options, {
|
|
@@ -83,21 +178,165 @@ interface GotStreamFunction {
|
|
|
83
178
|
isStream?: true;
|
|
84
179
|
}>): Request;
|
|
85
180
|
}
|
|
181
|
+
/**
|
|
182
|
+
An instance of `got.stream()`.
|
|
183
|
+
*/
|
|
86
184
|
export declare type GotStream = GotStreamFunction & Record<HTTPAlias, GotStreamFunction>;
|
|
185
|
+
/**
|
|
186
|
+
An instance of `got`.
|
|
187
|
+
*/
|
|
87
188
|
export interface Got extends Record<HTTPAlias, GotRequestFunction>, GotRequestFunction {
|
|
189
|
+
/**
|
|
190
|
+
Sets `options.isStream` to `true`.
|
|
191
|
+
|
|
192
|
+
Returns a [duplex stream](https://nodejs.org/api/stream.html#stream_class_stream_duplex) with additional events:
|
|
193
|
+
- request
|
|
194
|
+
- response
|
|
195
|
+
- redirect
|
|
196
|
+
- uploadProgress
|
|
197
|
+
- downloadProgress
|
|
198
|
+
- error
|
|
199
|
+
*/
|
|
88
200
|
stream: GotStream;
|
|
201
|
+
/**
|
|
202
|
+
Returns an async iterator.
|
|
203
|
+
|
|
204
|
+
See pagination.options for more pagination options.
|
|
205
|
+
|
|
206
|
+
@example
|
|
207
|
+
```
|
|
208
|
+
(async () => {
|
|
209
|
+
const countLimit = 10;
|
|
210
|
+
|
|
211
|
+
const pagination = got.paginate('https://api.github.com/repos/sindresorhus/got/commits', {
|
|
212
|
+
pagination: {countLimit}
|
|
213
|
+
});
|
|
214
|
+
|
|
215
|
+
console.log(`Printing latest ${countLimit} Got commits (newest to oldest):`);
|
|
216
|
+
|
|
217
|
+
for await (const commitData of pagination) {
|
|
218
|
+
console.log(commitData.commit.message);
|
|
219
|
+
}
|
|
220
|
+
})();
|
|
221
|
+
```
|
|
222
|
+
*/
|
|
89
223
|
paginate: GotPaginate;
|
|
224
|
+
/**
|
|
225
|
+
The Got defaults used in that instance.
|
|
226
|
+
*/
|
|
90
227
|
defaults: InstanceDefaults;
|
|
228
|
+
/**
|
|
229
|
+
An error to be thrown when a cache method fails.
|
|
230
|
+
For example, if the database goes down or there's a filesystem error.
|
|
231
|
+
*/
|
|
91
232
|
CacheError: typeof CacheError;
|
|
233
|
+
/**
|
|
234
|
+
An error to be thrown when a request fails.
|
|
235
|
+
Contains a `code` property with error class code, like `ECONNREFUSED`.
|
|
236
|
+
*/
|
|
92
237
|
RequestError: typeof RequestError;
|
|
238
|
+
/**
|
|
239
|
+
An error to be thrown when reading from response stream fails.
|
|
240
|
+
*/
|
|
93
241
|
ReadError: typeof ReadError;
|
|
242
|
+
/**
|
|
243
|
+
An error to be thrown when server response code is 2xx, and parsing body fails.
|
|
244
|
+
Includes a `response` property.
|
|
245
|
+
*/
|
|
94
246
|
ParseError: typeof ParseError;
|
|
247
|
+
/**
|
|
248
|
+
An error to be thrown when the server response code is not 2xx nor 3xx if `options.followRedirect` is `true`, but always except for 304.
|
|
249
|
+
Includes a `response` property.
|
|
250
|
+
*/
|
|
95
251
|
HTTPError: typeof HTTPError;
|
|
252
|
+
/**
|
|
253
|
+
An error to be thrown when the server redirects you more than ten times.
|
|
254
|
+
Includes a `response` property.
|
|
255
|
+
*/
|
|
96
256
|
MaxRedirectsError: typeof MaxRedirectsError;
|
|
257
|
+
/**
|
|
258
|
+
An error to be thrown when given an unsupported protocol.
|
|
259
|
+
*/
|
|
260
|
+
UnsupportedProtocolError: typeof UnsupportedProtocolError;
|
|
261
|
+
/**
|
|
262
|
+
An error to be thrown when the request is aborted due to a timeout.
|
|
263
|
+
Includes an `event` and `timings` property.
|
|
264
|
+
*/
|
|
97
265
|
TimeoutError: typeof TimeoutError;
|
|
266
|
+
/**
|
|
267
|
+
An error to be thrown when the request body is a stream and an error occurs while reading from that stream.
|
|
268
|
+
*/
|
|
269
|
+
UploadError: typeof UploadError;
|
|
270
|
+
/**
|
|
271
|
+
An error to be thrown when the request is aborted with `.cancel()`.
|
|
272
|
+
*/
|
|
98
273
|
CancelError: typeof CancelError;
|
|
274
|
+
/**
|
|
275
|
+
Configure a new `got` instance with default `options`.
|
|
276
|
+
The `options` are merged with the parent instance's `defaults.options` using `got.mergeOptions`.
|
|
277
|
+
You can access the resolved options with the `.defaults` property on the instance.
|
|
278
|
+
|
|
279
|
+
Additionally, `got.extend()` accepts two properties from the `defaults` object: `mutableDefaults` and `handlers`.
|
|
280
|
+
|
|
281
|
+
It is also possible to merges many instances into a single one:
|
|
282
|
+
- options are merged using `got.mergeOptions()` (including hooks),
|
|
283
|
+
- handlers are stored in an array (you can access them through `instance.defaults.handlers`).
|
|
284
|
+
|
|
285
|
+
@example
|
|
286
|
+
```js
|
|
287
|
+
const client = got.extend({
|
|
288
|
+
prefixUrl: 'https://example.com',
|
|
289
|
+
headers: {
|
|
290
|
+
'x-unicorn': 'rainbow'
|
|
291
|
+
}
|
|
292
|
+
});
|
|
293
|
+
|
|
294
|
+
client.get('demo');
|
|
295
|
+
|
|
296
|
+
// HTTP Request =>
|
|
297
|
+
// GET /demo HTTP/1.1
|
|
298
|
+
// Host: example.com
|
|
299
|
+
// x-unicorn: rainbow
|
|
300
|
+
```
|
|
301
|
+
*/
|
|
99
302
|
extend: (...instancesOrOptions: Array<Got | ExtendOptions>) => Got;
|
|
303
|
+
/**
|
|
304
|
+
Merges multiple `got` instances into the parent.
|
|
305
|
+
*/
|
|
100
306
|
mergeInstances: (parent: Got, ...instances: Got[]) => Got;
|
|
307
|
+
/**
|
|
308
|
+
Extends parent options.
|
|
309
|
+
Avoid using [object spread](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals) as it doesn't work recursively.
|
|
310
|
+
|
|
311
|
+
Options are deeply merged to a new object. The value of each key is determined as follows:
|
|
312
|
+
|
|
313
|
+
- If the new property is not defined, the old value is used.
|
|
314
|
+
- If the new property is explicitly set to `undefined`:
|
|
315
|
+
- If the parent property is a plain `object`, the parent value is deeply cloned.
|
|
316
|
+
- Otherwise, `undefined` is used.
|
|
317
|
+
- If the parent value is an instance of `URLSearchParams`:
|
|
318
|
+
- If the new value is a `string`, an `object` or an instance of `URLSearchParams`, a new `URLSearchParams` instance is created.
|
|
319
|
+
The values are merged using [`urlSearchParams.append(key, value)`](https://developer.mozilla.org/en-US/docs/Web/API/URLSearchParams/append).
|
|
320
|
+
The keys defined in the new value override the keys defined in the parent value.
|
|
321
|
+
- Otherwise, the only available value is `undefined`.
|
|
322
|
+
- If the new property is a plain `object`:
|
|
323
|
+
- If the parent property is a plain `object` too, both values are merged recursively into a new `object`.
|
|
324
|
+
- Otherwise, only the new value is deeply cloned.
|
|
325
|
+
- If the new property is an `Array`, it overwrites the old one with a deep clone of the new property.
|
|
326
|
+
- Properties that are not enumerable, such as `context`, `body`, `json`, and `form`, will not be merged.
|
|
327
|
+
- Otherwise, the new value is assigned to the key.
|
|
328
|
+
|
|
329
|
+
**Note:** Only Got options are merged! Custom user options should be defined via [`options.context`](#context).
|
|
330
|
+
|
|
331
|
+
@example
|
|
332
|
+
```
|
|
333
|
+
const a = {headers: {cat: 'meow', wolf: ['bark', 'wrrr']}};
|
|
334
|
+
const b = {headers: {cow: 'moo', wolf: ['auuu']}};
|
|
335
|
+
|
|
336
|
+
{...a, ...b} // => {headers: {cow: 'moo', wolf: ['auuu']}}
|
|
337
|
+
got.mergeOptions(a, b) // => {headers: {cat: 'meow', cow: 'moo', wolf: ['auuu']}}
|
|
338
|
+
```
|
|
339
|
+
*/
|
|
101
340
|
mergeOptions: (...sources: Options[]) => NormalizedOptions;
|
|
102
341
|
}
|
|
103
342
|
export {};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "got",
|
|
3
|
-
"version": "11.
|
|
3
|
+
"version": "11.6.0",
|
|
4
4
|
"description": "Human-friendly and powerful HTTP request library for Node.js",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": "sindresorhus/got",
|
|
@@ -43,14 +43,14 @@
|
|
|
43
43
|
"ky"
|
|
44
44
|
],
|
|
45
45
|
"dependencies": {
|
|
46
|
-
"@sindresorhus/is": "^3.
|
|
46
|
+
"@sindresorhus/is": "^3.1.1",
|
|
47
47
|
"@szmarczak/http-timer": "^4.0.5",
|
|
48
48
|
"@types/cacheable-request": "^6.0.1",
|
|
49
49
|
"@types/responselike": "^1.0.0",
|
|
50
50
|
"cacheable-lookup": "^5.0.3",
|
|
51
51
|
"cacheable-request": "^7.0.1",
|
|
52
52
|
"decompress-response": "^6.0.0",
|
|
53
|
-
"http2-wrapper": "^1.0.0-beta.5.
|
|
53
|
+
"http2-wrapper": "^1.0.0-beta.5.2",
|
|
54
54
|
"lowercase-keys": "^2.0.0",
|
|
55
55
|
"p-cancelable": "^2.0.0",
|
|
56
56
|
"responselike": "^2.0.0"
|
|
@@ -60,34 +60,38 @@
|
|
|
60
60
|
"@sindresorhus/tsconfig": "^0.7.0",
|
|
61
61
|
"@sinonjs/fake-timers": "^6.0.1",
|
|
62
62
|
"@types/benchmark": "^1.0.33",
|
|
63
|
-
"@types/express": "^4.17.
|
|
64
|
-
"@types/node": "^14.0
|
|
63
|
+
"@types/express": "^4.17.7",
|
|
64
|
+
"@types/node": "^14.6.0",
|
|
65
65
|
"@types/node-fetch": "^2.5.7",
|
|
66
|
+
"@types/pem": "^1.9.5",
|
|
67
|
+
"@types/pify": "^3.0.2",
|
|
66
68
|
"@types/request": "^2.48.5",
|
|
67
|
-
"@types/sinon": "^9.0.
|
|
69
|
+
"@types/sinon": "^9.0.5",
|
|
68
70
|
"@types/tough-cookie": "^4.0.0",
|
|
69
|
-
"ava": "^3.
|
|
70
|
-
"axios": "^0.
|
|
71
|
+
"ava": "^3.11.1",
|
|
72
|
+
"axios": "^0.20.0",
|
|
71
73
|
"benchmark": "^2.1.4",
|
|
72
74
|
"coveralls": "^3.1.0",
|
|
73
75
|
"create-test-server": "^3.0.1",
|
|
74
76
|
"del-cli": "^3.0.1",
|
|
75
|
-
"delay": "^4.
|
|
77
|
+
"delay": "^4.4.0",
|
|
76
78
|
"express": "^4.17.1",
|
|
77
79
|
"form-data": "^3.0.0",
|
|
78
|
-
"get-stream": "^
|
|
79
|
-
"nock": "^13.0.
|
|
80
|
+
"get-stream": "^6.0.0",
|
|
81
|
+
"nock": "^13.0.4",
|
|
80
82
|
"node-fetch": "^2.6.0",
|
|
81
|
-
"np": "^6.
|
|
83
|
+
"np": "^6.4.0",
|
|
82
84
|
"nyc": "^15.1.0",
|
|
83
85
|
"p-event": "^4.2.0",
|
|
84
|
-
"
|
|
86
|
+
"pem": "^1.14.4",
|
|
87
|
+
"pify": "^5.0.0",
|
|
88
|
+
"sinon": "^9.0.3",
|
|
85
89
|
"slow-stream": "0.0.4",
|
|
86
|
-
"tempy": "^0.
|
|
90
|
+
"tempy": "^0.6.0",
|
|
87
91
|
"to-readable-stream": "^2.1.0",
|
|
88
92
|
"tough-cookie": "^4.0.0",
|
|
89
|
-
"typescript": "
|
|
90
|
-
"xo": "^0.
|
|
93
|
+
"typescript": "^4.0.2",
|
|
94
|
+
"xo": "^0.33.0"
|
|
91
95
|
},
|
|
92
96
|
"types": "dist/source",
|
|
93
97
|
"sideEffects": false,
|
package/readme.md
CHANGED
|
@@ -40,7 +40,7 @@ For browser usage, we recommend [Ky](https://github.com/sindresorhus/ky) by the
|
|
|
40
40
|
- [Errors with metadata](#errors)
|
|
41
41
|
- [JSON mode](#json-mode)
|
|
42
42
|
- [WHATWG URL support](#url)
|
|
43
|
-
- [HTTPS API](#https)
|
|
43
|
+
- [HTTPS API](#advanced-https-api)
|
|
44
44
|
- [Hooks](#hooks)
|
|
45
45
|
- [Instances with custom defaults](#instances)
|
|
46
46
|
- [Types](#types)
|
|
@@ -510,12 +510,10 @@ Default:
|
|
|
510
510
|
|
|
511
511
|
An object representing `limit`, `calculateDelay`, `methods`, `statusCodes`, `maxRetryAfter` and `errorCodes` fields for maximum retry count, retry handler, allowed methods, allowed status codes, maximum [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) time and allowed error codes.
|
|
512
512
|
|
|
513
|
-
**Note:** When using streams, this option is ignored. If the connection is reset when downloading, you need to catch the error and clear the file you were writing into to prevent duplicated content.
|
|
514
|
-
|
|
515
513
|
If `maxRetryAfter` is set to `undefined`, it will use `options.timeout`.\
|
|
516
514
|
If [`Retry-After`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Retry-After) header is greater than `maxRetryAfter`, it will cancel the request.
|
|
517
515
|
|
|
518
|
-
Delays between retries counts with function `1000 * Math.pow(2, retry) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
|
|
516
|
+
Delays between retries counts with function `1000 * Math.pow(2, retry - 1) + Math.random() * 100`, where `retry` is attempt number (starts from 1).
|
|
519
517
|
|
|
520
518
|
The `calculateDelay` property is a `function` that receives an object with `attemptCount`, `retryOptions`, `error` and `computedValue` properties for current retry count, the retry options, error and default computed value. The function must return a delay in milliseconds (or a Promise resolving with it) (`0` return value cancels retry).
|
|
521
519
|
|
|
@@ -529,6 +527,36 @@ By default, it retries *only* on the specified methods, status codes, and on the
|
|
|
529
527
|
- `ENETUNREACH`: No internet connection.
|
|
530
528
|
- `EAI_AGAIN`: DNS lookup timed out.
|
|
531
529
|
|
|
530
|
+
<a name="retry-stream"></a>
|
|
531
|
+
|
|
532
|
+
You can retry Got streams too. The implementation looks like this:
|
|
533
|
+
|
|
534
|
+
```js
|
|
535
|
+
const got = require('got');
|
|
536
|
+
const fs = require('fs');
|
|
537
|
+
|
|
538
|
+
let writeStream;
|
|
539
|
+
|
|
540
|
+
const fn = (retryCount = 0) => {
|
|
541
|
+
const stream = got.stream('https://example.com');
|
|
542
|
+
stream.retryCount = retryCount;
|
|
543
|
+
|
|
544
|
+
if (writeStream) {
|
|
545
|
+
writeStream.destroy();
|
|
546
|
+
}
|
|
547
|
+
|
|
548
|
+
writeStream = fs.createWriteStream('example.com');
|
|
549
|
+
|
|
550
|
+
stream.pipe(writeStream);
|
|
551
|
+
|
|
552
|
+
// If you don't attach the listener, it will NOT make a retry.
|
|
553
|
+
// It automatically checks the listener count so it knows whether to retry or not :)
|
|
554
|
+
stream.once('retry', fn);
|
|
555
|
+
};
|
|
556
|
+
|
|
557
|
+
fn();
|
|
558
|
+
```
|
|
559
|
+
|
|
532
560
|
###### followRedirect
|
|
533
561
|
|
|
534
562
|
Type: `boolean`\
|
|
@@ -579,6 +607,13 @@ Default: `false`
|
|
|
579
607
|
|
|
580
608
|
[Cache adapter instance](#cache-adapters) for storing cached response data.
|
|
581
609
|
|
|
610
|
+
###### cacheOptions
|
|
611
|
+
|
|
612
|
+
Type: `object | undefined`\
|
|
613
|
+
Default: `{}`
|
|
614
|
+
|
|
615
|
+
[Cache options](https://github.com/kornelski/http-cache-semantics#constructor-options) used for the specified request.
|
|
616
|
+
|
|
582
617
|
###### dnsCache
|
|
583
618
|
|
|
584
619
|
Type: `CacheableLookup | false`\
|
|
@@ -1250,6 +1285,13 @@ If the `content-length` header is missing, `total` will be `undefined`.
|
|
|
1250
1285
|
})();
|
|
1251
1286
|
```
|
|
1252
1287
|
|
|
1288
|
+
##### .once('retry', retryCount, error)
|
|
1289
|
+
|
|
1290
|
+
To enable retrying on a Got stream, it is required to have a `retry` handler attached.\
|
|
1291
|
+
When this event is emitted, you should reset the stream you were writing to and prepare the body again.
|
|
1292
|
+
|
|
1293
|
+
See the [`retry`](#retry-stream) option for an example implementation.
|
|
1294
|
+
|
|
1253
1295
|
##### .ip
|
|
1254
1296
|
|
|
1255
1297
|
Type: `string`
|
|
@@ -1574,7 +1616,7 @@ Additionaly, the errors may have `request` (Got Stream) and `response` (Got Resp
|
|
|
1574
1616
|
|
|
1575
1617
|
#### got.RequestError
|
|
1576
1618
|
|
|
1577
|
-
When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`.
|
|
1619
|
+
When a request fails. Contains a `code` property with error class code, like `ECONNREFUSED`. All the errors below inherit this one.
|
|
1578
1620
|
|
|
1579
1621
|
#### got.CacheError
|
|
1580
1622
|
|
|
@@ -1610,7 +1652,7 @@ When the request is aborted due to a [timeout](#timeout). Includes an `event` an
|
|
|
1610
1652
|
|
|
1611
1653
|
#### got.CancelError
|
|
1612
1654
|
|
|
1613
|
-
When the request is aborted with `.cancel()`.
|
|
1655
|
+
When the request is aborted with `.cancel()`.
|
|
1614
1656
|
|
|
1615
1657
|
## Aborting the request
|
|
1616
1658
|
|
|
@@ -1889,6 +1931,32 @@ nock('https://sindresorhus.com')
|
|
|
1889
1931
|
})();
|
|
1890
1932
|
```
|
|
1891
1933
|
|
|
1934
|
+
Bear in mind, that by default `nock` mocks only one request. Got will [retry](#retry) on failed requests by default, causing a `No match for request ...` error. The solution is to either disable retrying (set `options.retry` to `0`) or call `.persist()` on the mocked request.
|
|
1935
|
+
|
|
1936
|
+
```js
|
|
1937
|
+
const got = require('got');
|
|
1938
|
+
const nock = require('nock');
|
|
1939
|
+
|
|
1940
|
+
const scope = nock('https://sindresorhus.com')
|
|
1941
|
+
.get('/')
|
|
1942
|
+
.reply(500, 'Internal server error')
|
|
1943
|
+
.persist();
|
|
1944
|
+
|
|
1945
|
+
(async () => {
|
|
1946
|
+
try {
|
|
1947
|
+
await got('https://sindresorhus.com')
|
|
1948
|
+
} catch (error) {
|
|
1949
|
+
console.log(error.response.body);
|
|
1950
|
+
//=> 'Internal server error'
|
|
1951
|
+
|
|
1952
|
+
console.log(error.response.retryCount);
|
|
1953
|
+
//=> 2
|
|
1954
|
+
}
|
|
1955
|
+
|
|
1956
|
+
scope.persist(false);
|
|
1957
|
+
})();
|
|
1958
|
+
```
|
|
1959
|
+
|
|
1892
1960
|
For real integration testing we recommend using [`ava`](https://github.com/avajs/ava) with [`create-test-server`](https://github.com/lukechilds/create-test-server). We're using a macro so we don't have to `server.listen()` and `server.close()` every test. Take a look at one of our tests:
|
|
1893
1961
|
|
|
1894
1962
|
```js
|
|
@@ -2046,7 +2114,7 @@ The Electron `net` module is not consistent with the Node.js `http` module. See
|
|
|
2046
2114
|
\* It's almost API compatible with the browser `fetch` API.\
|
|
2047
2115
|
\*\* Need to switch the protocol manually. Doesn't accept PUSH streams and doesn't reuse HTTP/2 sessions.\
|
|
2048
2116
|
\*\*\* Currently, only `DownloadProgress` event is supported, `UploadProgress` event is not supported.\
|
|
2049
|
-
:sparkle: Almost-stable feature, but the API may change. Don't
|
|
2117
|
+
:sparkle: Almost-stable feature, but the API may change. Don't hesitate to try it out!\
|
|
2050
2118
|
:grey_question: Feature in early stage of development. Very experimental.
|
|
2051
2119
|
|
|
2052
2120
|
<!-- GITHUB -->
|
|
@@ -1,38 +0,0 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
const types_1 = require("./types");
|
|
4
|
-
const retryAfterStatusCodes = new Set([413, 429, 503]);
|
|
5
|
-
const isErrorWithResponse = (error) => (error instanceof types_1.HTTPError || error instanceof types_1.ParseError || error instanceof types_1.MaxRedirectsError);
|
|
6
|
-
const calculateRetryDelay = ({ attemptCount, retryOptions, error }) => {
|
|
7
|
-
if (attemptCount > retryOptions.limit) {
|
|
8
|
-
return 0;
|
|
9
|
-
}
|
|
10
|
-
const hasMethod = retryOptions.methods.includes(error.options.method);
|
|
11
|
-
const hasErrorCode = retryOptions.errorCodes.includes(error.code);
|
|
12
|
-
const hasStatusCode = isErrorWithResponse(error) && retryOptions.statusCodes.includes(error.response.statusCode);
|
|
13
|
-
if (!hasMethod || (!hasErrorCode && !hasStatusCode)) {
|
|
14
|
-
return 0;
|
|
15
|
-
}
|
|
16
|
-
if (isErrorWithResponse(error)) {
|
|
17
|
-
const { response } = error;
|
|
18
|
-
if (response && 'retry-after' in response.headers && retryAfterStatusCodes.has(response.statusCode)) {
|
|
19
|
-
let after = Number(response.headers['retry-after']);
|
|
20
|
-
if (Number.isNaN(after)) {
|
|
21
|
-
after = Date.parse(response.headers['retry-after']) - Date.now();
|
|
22
|
-
}
|
|
23
|
-
else {
|
|
24
|
-
after *= 1000;
|
|
25
|
-
}
|
|
26
|
-
if (retryOptions.maxRetryAfter === undefined || after > retryOptions.maxRetryAfter) {
|
|
27
|
-
return 0;
|
|
28
|
-
}
|
|
29
|
-
return after;
|
|
30
|
-
}
|
|
31
|
-
if (response.statusCode === 413) {
|
|
32
|
-
return 0;
|
|
33
|
-
}
|
|
34
|
-
}
|
|
35
|
-
const noise = Math.random() * 100;
|
|
36
|
-
return ((2 ** (attemptCount - 1)) * 1000) + noise;
|
|
37
|
-
};
|
|
38
|
-
exports.default = calculateRetryDelay;
|
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/// <reference types="node" />
|
|
2
|
-
import { URL } from 'url';
|
|
3
|
-
import { Options, NormalizedOptions, Defaults, ResponseType, Response } from './types';
|
|
4
|
-
import Request, { ParseJsonFunction } from '../core';
|
|
5
|
-
export declare const knownBodyTypes: string[];
|
|
6
|
-
export declare const parseBody: (response: Response, responseType: ResponseType, parseJson: ParseJsonFunction, encoding?: "ascii" | "utf8" | "utf-8" | "utf16le" | "ucs2" | "ucs-2" | "base64" | "latin1" | "binary" | "hex" | undefined) => unknown;
|
|
7
|
-
export default class PromisableRequest extends Request {
|
|
8
|
-
['constructor']: typeof PromisableRequest;
|
|
9
|
-
options: NormalizedOptions;
|
|
10
|
-
static normalizeArguments(url?: string | URL, nonNormalizedOptions?: Options, defaults?: Defaults): NormalizedOptions;
|
|
11
|
-
static mergeOptions(...sources: Options[]): NormalizedOptions;
|
|
12
|
-
_beforeError(error: Error): void;
|
|
13
|
-
}
|