forked from sindresorhus/got
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathas-promise.ts
176 lines (140 loc) · 5 KB
/
as-promise.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
import {IncomingMessage} from 'http';
import EventEmitter = require('events');
import getStream = require('get-stream');
import is from '@sindresorhus/is';
import PCancelable = require('p-cancelable');
import {NormalizedOptions, Response, CancelableRequest} from './utils/types';
import {ParseError, ReadError, HTTPError} from './errors';
import requestAsEventEmitter, {proxyEvents} from './request-as-event-emitter';
import {normalizeArguments, mergeOptions} from './normalize-arguments';
const parseBody = (body: Response['body'], responseType: NormalizedOptions['responseType'], statusCode: Response['statusCode']) => {
if (responseType === 'json' && is.string(body)) {
return statusCode === 204 ? '' : JSON.parse(body);
}
if (responseType === 'buffer' && is.string(body)) {
return Buffer.from(body);
}
if (responseType === 'text') {
return String(body);
}
if (responseType === 'default') {
return body;
}
throw new Error(`Failed to parse body of type '${typeof body}' as '${responseType}'`);
};
export default function asPromise(options: NormalizedOptions) {
const proxy = new EventEmitter();
let finalResponse: Pick<Response, 'body' | 'statusCode'>;
// @ts-ignore `.json()`, `.buffer()` and `.text()` are added later
const promise = new PCancelable<IncomingMessage | Response['body']>((resolve, reject, onCancel) => {
const emitter = requestAsEventEmitter(options);
onCancel(emitter.abort);
const emitError = async (error: Error): Promise<void> => {
try {
for (const hook of options.hooks.beforeError) {
// eslint-disable-next-line no-await-in-loop
error = await hook(error);
}
reject(error);
} catch (error_) {
reject(error_);
}
};
emitter.on('response', async (response: Response) => {
proxy.emit('response', response);
const streamAsPromise = is.null_(options.encoding) ? getStream.buffer(response) : getStream(response, {encoding: options.encoding});
try {
response.body = await streamAsPromise;
} catch (error) {
emitError(new ReadError(error, options));
return;
}
if (response.req?.aborted) {
// Canceled while downloading - will throw a `CancelError` or `TimeoutError` error
return;
}
try {
for (const [index, hook] of options.hooks.afterResponse.entries()) {
// @ts-ignore
// eslint-disable-next-line no-await-in-loop
response = await hook(response, async (updatedOptions: NormalizedOptions) => {
updatedOptions = normalizeArguments(mergeOptions(options, {
...updatedOptions,
retry: {
calculateDelay: () => 0
},
throwHttpErrors: false,
responseType: 'text',
resolveBodyOnly: false
}));
// Remove any further hooks for that request, because we we'll call them anyway.
// The loop continues. We don't want duplicates (asPromise recursion).
updatedOptions.hooks.afterResponse = options.hooks.afterResponse.slice(0, index);
for (const hook of options.hooks.beforeRetry) {
// eslint-disable-next-line no-await-in-loop
await hook(updatedOptions);
}
const promise = asPromise(updatedOptions);
onCancel(() => {
promise.catch(() => {});
promise.cancel();
});
return promise;
});
}
} catch (error) {
emitError(error);
return;
}
const {statusCode} = response;
finalResponse = {
body: response.body,
statusCode
};
try {
response.body = parseBody(response.body, options.responseType, response.statusCode);
} catch (error) {
if (statusCode >= 200 && statusCode < 300) {
const parseError = new ParseError(error, response, options);
emitError(parseError);
return;
}
}
const limitStatusCode = options.followRedirect ? 299 : 399;
if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
const error = new HTTPError(response, options);
if (emitter.retry(error) === false) {
if (options.throwHttpErrors) {
emitError(error);
return;
}
resolve(options.resolveBodyOnly ? response.body : response);
}
return;
}
resolve(options.resolveBodyOnly ? response.body : response);
});
emitter.once('error', reject);
proxyEvents(proxy, emitter);
}) as CancelableRequest<any>;
promise.on = (name: string, fn: (...args: any[]) => void) => {
proxy.on(name, fn);
return promise;
};
const shortcut = (responseType: NormalizedOptions['responseType']): CancelableRequest<any> => {
// eslint-disable-next-line promise/prefer-await-to-then
const newPromise = promise.then(() => parseBody(finalResponse.body, responseType, finalResponse.statusCode));
Object.defineProperties(newPromise, Object.getOwnPropertyDescriptors(promise));
// @ts-ignore The missing properties are added above
return newPromise;
};
promise.json = () => {
if (is.undefined(options.headers.accept)) {
options.headers.accept = 'application/json';
}
return shortcut('json');
};
promise.buffer = () => shortcut('buffer');
promise.text = () => shortcut('text');
return promise;
}