/
as-promise.ts
142 lines (117 loc) 路 3.95 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
import {IncomingMessage} from 'http';
import EventEmitter from 'events';
import getStream from 'get-stream';
import is from '@sindresorhus/is';
import PCancelable from 'p-cancelable';
import requestAsEventEmitter from './request-as-event-emitter';
import {HTTPError, ParseError, ReadError} from './errors';
import {mergeOptions} from './merge';
import {reNormalizeArguments} from './normalize-arguments';
import {CancelableRequest, Options, Response} from './utils/types';
export default function asPromise(options: Options) {
const proxy = new EventEmitter();
const parseBody = (response: Response) => {
if (options.responseType === 'json') {
response.body = JSON.parse(response.body as string);
} else if (options.responseType === 'buffer') {
response.body = Buffer.from(response.body as Buffer);
} else if (options.responseType !== 'text' && !is.falsy(options.responseType)) {
throw new Error(`Failed to parse body of type '${options.responseType}'`);
}
};
const promise = new PCancelable<IncomingMessage>((resolve, reject, onCancel) => {
const emitter = requestAsEventEmitter(options);
onCancel(emitter.abort);
emitter.on('response', async response => {
proxy.emit('response', response);
const stream = is.null_(options.encoding) ? getStream.buffer(response) : getStream(response, {encoding: options.encoding});
let data;
try {
data = await stream;
} catch (error) {
reject(new ReadError(error, options));
return;
}
if (response.req && response.req.aborted) {
// Canceled while downloading - will throw a CancelError or TimeoutError
return;
}
const limitStatusCode = options.followRedirect ? 299 : 399;
response.body = data;
try {
for (const [index, hook] of options.hooks!.afterResponse!.entries()) {
// eslint-disable-next-line no-await-in-loop
response = await hook(response, updatedOptions => {
updatedOptions = reNormalizeArguments(mergeOptions(options, {
...updatedOptions,
retry: 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);
return asPromise(updatedOptions);
});
}
} catch (error) {
reject(error);
return;
}
const {statusCode} = response;
if (response.body) {
try {
parseBody(response);
} catch (error) {
if (statusCode >= 200 && statusCode < 300) {
const parseError = new ParseError(error, statusCode, options, data);
Object.defineProperty(parseError, 'response', {value: response});
reject(parseError);
return;
}
}
}
if (statusCode !== 304 && (statusCode < 200 || statusCode > limitStatusCode)) {
const error = new HTTPError(response, options);
Object.defineProperty(error, 'response', {value: response});
if (emitter.retry(error) === false) {
if (options.throwHttpErrors) {
reject(error);
return;
}
resolve(options.resolveBodyOnly ? response.body : response);
}
return;
}
resolve(options.resolveBodyOnly ? response.body : response);
});
emitter.once('error', reject);
[
'request',
'redirect',
'uploadProgress',
'downloadProgress'
].forEach(event => emitter.on(event, (...args) => proxy.emit(event, ...args)));
}) as CancelableRequest<IncomingMessage>;
promise.on = (name: string, fn: () => void) => {
proxy.on(name, fn);
return promise;
};
promise.json = () => {
options.responseType = 'json';
options.resolveBodyOnly = true;
return promise;
};
promise.buffer = () => {
options.responseType = 'buffer';
options.resolveBodyOnly = true;
return promise;
};
promise.text = () => {
options.responseType = 'text';
options.resolveBodyOnly = true;
return promise;
};
return promise;
}