-
-
Notifications
You must be signed in to change notification settings - Fork 935
/
index.ts
209 lines (164 loc) · 5.51 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
import {EventEmitter} from 'events';
import is from '@sindresorhus/is';
import PCancelable = require('p-cancelable');
import {
NormalizedOptions,
CancelableRequest,
Response,
RequestError,
HTTPError,
CancelError
} from './types';
import parseBody from './parse-body';
import Request from '../core';
import proxyEvents from '../core/utils/proxy-events';
import getBuffer from '../core/utils/get-buffer';
import {isResponseOk} from '../core/utils/is-response-ok';
const proxiedRequestEvents = [
'request',
'response',
'redirect',
'uploadProgress',
'downloadProgress'
];
export default function asPromise<T>(normalizedOptions: NormalizedOptions): CancelableRequest<T> {
let globalRequest: Request;
let globalResponse: Response;
const emitter = new EventEmitter();
const promise = new PCancelable<T>((resolve, reject, onCancel) => {
const makeRequest = (retryCount: number): void => {
const request = new Request(undefined, normalizedOptions);
request.retryCount = retryCount;
request._noPipe = true;
onCancel(() => request.destroy());
onCancel.shouldReject = false;
onCancel(() => reject(new CancelError(request)));
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;
}
// Download body
let rawBody;
try {
rawBody = await getBuffer(request);
response.rawBody = rawBody;
} catch {
// The same error is caught below.
// See request.once('error')
return;
}
if (request._isAboutToError) {
return;
}
// Parse body
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
const isCompressed = ['gzip', 'deflate', 'br'].includes(contentEncoding);
const {options} = request;
if (isCompressed && !options.decompress) {
response.body = rawBody;
} else {
try {
response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
} catch (error) {
// Fallback to `utf8`
response.body = rawBody.toString();
if (isResponseOk(response)) {
request._beforeError(error);
return;
}
}
}
try {
for (const [index, hook] of options.hooks.afterResponse.entries()) {
// @ts-expect-error 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.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(new RequestError(error.message, error, request));
return;
}
globalResponse = response;
if (!isResponseOk(response)) {
request._beforeError(new HTTPError(response));
return;
}
request.destroy();
resolve(request.options.resolveBodyOnly ? response.body as T : response as unknown as T);
});
const onError = (error: RequestError) => {
if (promise.isCanceled) {
return;
}
const {options} = request;
if (error instanceof HTTPError && !options.throwHttpErrors) {
const {response} = error;
resolve(request.options.resolveBodyOnly ? response.body as T : response as unknown as T);
return;
}
reject(error);
};
request.once('error', onError);
const previousBody = request.options.body;
request.once('retry', (newRetryCount: number, error: RequestError) => {
if (previousBody === error.request?.options.body && is.nodeStream(error.request?.options.body)) {
onError(error);
return;
}
makeRequest(newRetryCount);
});
proxyEvents(request, emitter, proxiedRequestEvents);
};
makeRequest(0);
}) 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;
const {options} = globalResponse.request;
return parseBody(globalResponse, responseType, options.parseJson, options.encoding);
})();
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise as CancelableRequest<T>;
};
promise.json = () => {
const {headers} = globalRequest.options;
if (!globalRequest.writableFinished && headers.accept === undefined) {
headers.accept = 'application/json';
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}
export * from './types';