-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
index.ts
205 lines (168 loc) 路 5.29 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
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,
ReadError,
ParseError
} from './types';
import PromisableRequest from './core';
import proxyEvents from '../utils/proxy-events';
export const knownBodyTypes = ['json', 'buffer', 'text'];
// @ts-ignore The error is: Not all code paths return a value.
const parseBody = (body: Buffer, responseType: NormalizedOptions['responseType'], encoding: NormalizedOptions['encoding']): unknown => {
if (responseType === 'text') {
return body.toString(encoding);
}
if (responseType === 'json') {
return body.length === 0 ? '' : JSON.parse(body.toString());
}
if (responseType === 'buffer') {
return Buffer.from(body);
}
if (!knownBodyTypes.includes(responseType)) {
throw new TypeError(`Unknown body type '${responseType as string}'`);
}
};
export default function asPromise<T>(options: NormalizedOptions): CancelableRequest<T> {
let retryCount = 0;
let body: Buffer;
const emitter = new EventEmitter();
const promise = new PCancelable<T>((resolve, reject, onCancel) => {
const makeRequest = (): void => {
const request = new PromisableRequest(options.url, options);
onCancel(request.destroy);
request.once('response', async (response: Response) => {
// Download body
try {
body = await getStream.buffer(response, {encoding: 'binary'});
} catch (error) {
request._beforeError(new ReadError(error, options, response));
return;
}
if (response.request.aborted) {
// Canceled while downloading - will throw a `CancelError` or `TimeoutError` error
return;
}
// Parse body
try {
response.body = parseBody(body, options.responseType, options.encoding);
} catch (error) {
response.body = body.toString();
const parseError = new ParseError(error, response, options);
request._beforeError(parseError);
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 = request.constructor.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) {
request._beforeError(error);
return;
}
resolve(options.resolveBodyOnly ? response.body as T : response as unknown as T);
});
request.once('error', (error: RequestError) => {
if (error instanceof HTTPError) {
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_) {
request._beforeError(error_);
return;
}
if (backoff) {
const retry = async (): Promise<void> => {
try {
for (const hook of options.hooks.beforeRetry) {
await hook(options, error, retryCount);
}
} catch (error_) {
request._beforeError(error_);
return;
}
makeRequest();
};
setTimeout(retry, backoff);
return;
}
}
reject(error);
});
if (!('body' in options)) {
request.end();
}
proxyEvents(request, emitter, [
'request',
'redirect',
'uploadProgress',
'downloadProgress'
]);
};
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 () => {
await promise;
return parseBody(body, responseType, options.encoding);
})();
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise as CancelableRequest<T>;
};
promise.json = () => {
if (body === undefined && 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};