-
-
Notifications
You must be signed in to change notification settings - Fork 957
/
Copy pathindex.ts
265 lines (213 loc) · 6.8 KB
/
index.ts
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
import {EventEmitter} from 'events';
import getStream = require('get-stream');
import PCancelable = require('p-cancelable');
import calculateRetryDelay from './calculate-retry-delay';
import {
NormalizedOptions,
CancelableRequest,
Response,
RequestError,
HTTPError
} from './types';
import PromisableRequest, {parseBody} from './core';
import proxyEvents from '../core/utils/proxy-events';
const proxiedRequestEvents = [
'request',
'response',
'redirect',
'uploadProgress',
'downloadProgress'
];
export default function asPromise<T>(options: NormalizedOptions): CancelableRequest<T> {
let retryCount = 0;
let globalRequest: PromisableRequest;
let globalResponse: Response;
const emitter = new EventEmitter();
const promise = new PCancelable<T>((resolve, _reject, onCancel) => {
const makeRequest = (): void => {
// Support retries
// `options.throwHttpErrors` needs to be always true,
// so the HTTP errors are caught and the request is retried.
// The error is **eventually** thrown if the user value is true.
const {throwHttpErrors} = options;
if (!throwHttpErrors) {
options.throwHttpErrors = true;
}
// Note from @szmarczak: I think we should use `request.options` instead of the local options
const request = new PromisableRequest(options.url, options);
request._noPipe = true;
onCancel(() => request.destroy());
const reject = async (error: RequestError) => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
} catch (error_) {
_reject(new RequestError(error_.message, error_, request));
return;
}
_reject(error);
};
globalRequest = request;
request.once('response', async (response: Response) => {
response.retryCount = retryCount;
if (response.request.aborted) {
// Canceled while downloading - will throw a `CancelError` or `TimeoutError` error
return;
}
const isOk = (): boolean => {
const {statusCode} = response;
const limitStatusCode = options.followRedirect ? 299 : 399;
return (statusCode >= 200 && statusCode <= limitStatusCode) || statusCode === 304;
};
// Download body
let rawBody;
try {
rawBody = await getStream.buffer(request);
response.rawBody = rawBody;
} catch (_) {
// The same error is caught below.
// See request.once('error')
return;
}
// Parse body
try {
response.body = parseBody(response, options.responseType, options.encoding);
} catch (error) {
// Fallback to `utf8`
response.body = rawBody.toString();
if (isOk()) {
// TODO: Call `request._beforeError`, see https://github.com/nodejs/node/issues/32995
reject(error);
return;
}
}
try {
for (const [index, hook] of options.hooks.afterResponse.entries()) {
// @ts-ignore TS doesn't notice that CancelableRequest is a Promise
// eslint-disable-next-line no-await-in-loop
response = await hook(response, async (updatedOptions): CancelableRequest<Response> => {
const typedOptions = PromisableRequest.normalizeArguments(undefined, {
...updatedOptions,
retry: {
calculateDelay: () => 0
},
throwHttpErrors: false,
resolveBodyOnly: false
}, options);
// Remove any further hooks for that request, because we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
typedOptions.hooks.afterResponse = typedOptions.hooks.afterResponse.slice(0, index);
for (const hook of typedOptions.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(typedOptions);
}
const promise: CancelableRequest<Response> = asPromise(typedOptions);
onCancel(() => {
promise.catch(() => {});
promise.cancel();
});
return promise;
});
}
} catch (error) {
// TODO: Call `request._beforeError`, see https://github.com/nodejs/node/issues/32995
reject(new RequestError(error.message, error, request));
return;
}
if (throwHttpErrors && !isOk()) {
reject(new HTTPError(response));
return;
}
globalResponse = response;
resolve(options.resolveBodyOnly ? response.body as T : response as unknown as T);
});
request.once('error', (error: RequestError) => {
if (promise.isCanceled) {
return;
}
if (!request.options) {
reject(error);
return;
}
let backoff: number;
retryCount++;
try {
backoff = options.retry.calculateDelay({
attemptCount: retryCount,
retryOptions: options.retry,
error,
computedValue: calculateRetryDelay({
attemptCount: retryCount,
retryOptions: options.retry,
error,
computedValue: 0
})
});
} catch (error_) {
// Don't emit the `response` event
request.destroy();
reject(new RequestError(error_.message, error, request));
return;
}
if (backoff) {
// Don't emit the `response` event
request.destroy();
const retry = async (): Promise<void> => {
options.throwHttpErrors = throwHttpErrors;
try {
for (const hook of options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(options, error, retryCount);
}
} catch (error_) {
// Don't emit the `response` event
request.destroy();
reject(new RequestError(error_.message, error, request));
return;
}
makeRequest();
};
setTimeout(retry, backoff);
return;
}
// The retry has not been made
retryCount--;
if (error instanceof HTTPError) {
// It will be handled by the `response` event
return;
}
// Don't emit the `response` event
request.destroy();
reject(error);
});
proxyEvents(request, emitter, proxiedRequestEvents);
};
makeRequest();
}) as CancelableRequest<T>;
promise.on = (event: string, fn: (...args: any[]) => void) => {
emitter.on(event, fn);
return promise;
};
const shortcut = <T>(responseType: NormalizedOptions['responseType']): CancelableRequest<T> => {
const newPromise = (async () => {
// Wait until downloading has ended
await promise;
return parseBody(globalResponse, responseType, options.encoding);
})();
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise as CancelableRequest<T>;
};
promise.json = () => {
if (!globalRequest.writableFinished && options.headers.accept === undefined) {
options.headers.accept = 'application/json';
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}
export * from './types';
export {PromisableRequest};