forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
205 lines (158 loc) · 5.65 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 'node:events';
import is from '@sindresorhus/is';
import PCancelable from 'p-cancelable';
import {
RequestError,
HTTPError,
RetryError,
} from '../core/errors.js';
import Request from '../core/index.js';
import {parseBody, isResponseOk} from '../core/response.js';
import proxyEvents from '../core/utils/proxy-events.js';
import type Options from '../core/options.js';
import type {Response} from '../core/response.js';
import {CancelError} from './types.js';
import type {CancelableRequest} from './types.js';
const proxiedRequestEvents = [
'request',
'response',
'redirect',
'uploadProgress',
'downloadProgress',
];
export default function asPromise<T>(firstRequest?: Request): CancelableRequest<T> {
let globalRequest: Request;
let globalResponse: Response;
let normalizedOptions: Options;
const emitter = new EventEmitter();
const promise = new PCancelable<T>((resolve, reject, onCancel) => {
onCancel(() => {
globalRequest.destroy();
});
onCancel.shouldReject = false;
onCancel(() => {
reject(new CancelError(globalRequest));
});
const makeRequest = (retryCount: number): void => {
// Errors when a new request is made after the promise settles.
// Used to detect a race condition.
// See https://github.com/sindresorhus/got/issues/1489
onCancel(() => {});
const request = firstRequest ?? new Request(undefined, undefined, normalizedOptions);
request.retryCount = retryCount;
request._noPipe = true;
globalRequest = request;
request.once('response', async (response: Response) => {
// Parse body
const contentEncoding = (response.headers['content-encoding'] ?? '').toLowerCase();
const isCompressed = contentEncoding === 'gzip' || contentEncoding === 'deflate' || contentEncoding === 'br';
const {options} = request;
if (isCompressed && !options.decompress) {
response.body = response.rawBody;
} else {
try {
response.body = parseBody(response, options.responseType, options.parseJson, options.encoding);
} catch (error: any) {
// Fall back to `utf8`
response.body = response.rawBody.toString();
if (isResponseOk(response)) {
request._beforeError(error);
return;
}
}
}
try {
const hooks = options.hooks.afterResponse;
for (const [index, hook] of hooks.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> => {
options.merge(updatedOptions);
options.prefixUrl = '';
if (updatedOptions.url) {
options.url = updatedOptions.url;
}
// Remove any further hooks for that request, because we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
options.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
throw new RetryError(request);
});
if (!(is.object(response) && is.number(response.statusCode) && !is.nullOrUndefined(response.body))) {
throw new TypeError('The `afterResponse` hook returned an invalid value');
}
}
} catch (error: any) {
request._beforeError(error);
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;
request.destroy();
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) => {
firstRequest = undefined;
const newBody = request.options.body;
if (previousBody === newBody && is.nodeStream(newBody)) {
error.message = 'Cannot retry with consumed body stream';
onError(error);
return;
}
// This is needed! We need to reuse `request.options` because they can get modified!
// For example, by calling `promise.json()`.
normalizedOptions = request.options;
makeRequest(newRetryCount);
});
proxyEvents(request, emitter, proxiedRequestEvents);
if (is.undefined(firstRequest)) {
void request.flush();
}
};
makeRequest(0);
}) as CancelableRequest<T>;
promise.on = (event: string, fn: (...args: any[]) => void) => {
emitter.on(event, fn);
return promise;
};
const shortcut = <T>(responseType: Options['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);
})();
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
return newPromise as CancelableRequest<T>;
};
promise.json = () => {
if (globalRequest.options) {
const {headers} = globalRequest.options;
if (!globalRequest.writableFinished && !('accept' in headers)) {
headers.accept = 'application/json';
}
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}