-
-
Notifications
You must be signed in to change notification settings - Fork 916
/
core.ts
157 lines (127 loc) 路 4.31 KB
/
core.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
import {URL} from 'url';
import is, {assert} from '@sindresorhus/is';
import {
Options,
NormalizedOptions,
Defaults,
ResponseType,
ParseError,
Response
} from './types';
import Request, {knownHookEvents, RequestError, Method} from '../core';
if (!knownHookEvents.includes('beforeRetry' as any)) {
knownHookEvents.push('beforeRetry' as any, 'afterResponse' as any);
}
export const knownBodyTypes = ['json', 'buffer', 'text'];
// @ts-ignore The error is: Not all code paths return a value.
export const parseBody = (response: Response, responseType: ResponseType, encoding?: string): unknown => {
const {rawBody} = response;
try {
if (responseType === 'text') {
return rawBody.toString(encoding);
}
if (responseType === 'json') {
return rawBody.length === 0 ? '' : JSON.parse(rawBody.toString()) as unknown;
}
if (responseType === 'buffer') {
return Buffer.from(rawBody);
}
throw new ParseError({
message: `Unknown body type '${responseType as string}'`,
name: 'Error'
}, response);
} catch (error) {
throw new ParseError(error, response);
}
};
export default class PromisableRequest extends Request {
['constructor']: typeof PromisableRequest;
declare options: NormalizedOptions;
static normalizeArguments(url?: string | URL, nonNormalizedOptions?: Options, defaults?: Defaults): NormalizedOptions {
const options = super.normalizeArguments(url, nonNormalizedOptions, defaults) as NormalizedOptions;
if (is.null_(options.encoding)) {
throw new TypeError('To get a Buffer, set `options.responseType` to `buffer` instead');
}
assert.any([is.string, is.undefined], options.encoding);
assert.any([is.boolean, is.undefined], options.resolveBodyOnly);
assert.any([is.boolean, is.undefined], options.methodRewriting);
assert.any([is.boolean, is.undefined], options.isStream);
assert.any([is.string, is.undefined], options.responseType);
// `options.responseType`
if (options.responseType === undefined) {
options.responseType = 'text';
}
// `options.retry`
const {retry} = options;
if (defaults) {
options.retry = {...defaults.retry};
} else {
options.retry = {
calculateDelay: retryObject => retryObject.computedValue,
limit: 0,
methods: [],
statusCodes: [],
errorCodes: [],
maxRetryAfter: undefined
};
}
if (is.object(retry)) {
options.retry = {
...options.retry,
...retry
};
options.retry.methods = [...new Set(options.retry.methods.map(method => method.toUpperCase() as Method))];
options.retry.statusCodes = [...new Set(options.retry.statusCodes)];
options.retry.errorCodes = [...new Set(options.retry.errorCodes)];
} else if (is.number(retry)) {
options.retry.limit = retry;
}
if (is.undefined(options.retry.maxRetryAfter)) {
options.retry.maxRetryAfter = Math.min(
...[options.timeout.request, options.timeout.connect].filter(is.number)
);
}
// `options.pagination`
if (is.object(options.pagination)) {
if (defaults) {
(options as Options).pagination = {
...defaults.pagination,
...options.pagination
};
}
const {pagination} = options;
if (!is.function_(pagination.transform)) {
throw new Error('`options.pagination.transform` must be implemented');
}
if (!is.function_(pagination.shouldContinue)) {
throw new Error('`options.pagination.shouldContinue` must be implemented');
}
if (!is.function_(pagination.filter)) {
throw new TypeError('`options.pagination.filter` must be implemented');
}
if (!is.function_(pagination.paginate)) {
throw new Error('`options.pagination.paginate` must be implemented');
}
}
// JSON mode
if (options.responseType === 'json' && options.headers.accept === undefined) {
options.headers.accept = 'application/json';
}
return options;
}
static mergeOptions(...sources: Options[]): NormalizedOptions {
let mergedOptions: NormalizedOptions | undefined;
for (const source of sources) {
mergedOptions = PromisableRequest.normalizeArguments(undefined, source, mergedOptions);
}
return mergedOptions!;
}
async _beforeError(error: Error): Promise<void> {
if (!(error instanceof RequestError)) {
error = new RequestError(error.message, error, this);
}
// Let the promise decide whether to abort or not
// It is also responsible for the `beforeError` hook
this.emit('error', error);
}
}