-
-
Notifications
You must be signed in to change notification settings - Fork 935
/
create.ts
247 lines (192 loc) · 6.36 KB
/
create.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
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
import {setTimeout as delay} from 'node:timers/promises';
import is, {assert} from '@sindresorhus/is';
import asPromise from './as-promise/index.js';
import type {
GotReturn,
ExtendOptions,
Got,
HTTPAlias,
InstanceDefaults,
GotPaginate,
GotStream,
GotRequestFunction,
OptionsWithPagination,
StreamOptions,
} from './types.js';
import Request from './core/index.js';
import type {Response} from './core/response.js';
import Options, {type OptionsInit} from './core/options.js';
import type {CancelableRequest} from './as-promise/types.js';
const isGotInstance = (value: Got | ExtendOptions): value is Got => is.function(value);
const aliases: readonly HTTPAlias[] = [
'get',
'post',
'put',
'patch',
'head',
'delete',
];
const create = (defaults: InstanceDefaults): Got => {
defaults = {
options: new Options(undefined, undefined, defaults.options),
handlers: [...defaults.handlers],
mutableDefaults: defaults.mutableDefaults,
};
Object.defineProperty(defaults, 'mutableDefaults', {
enumerable: true,
configurable: false,
writable: false,
});
// Got interface
const got: Got = ((url: string | URL | OptionsInit | undefined, options?: OptionsInit, defaultOptions: Options = defaults.options): GotReturn => {
const request = new Request(url, options, defaultOptions);
let promise: CancelableRequest | undefined;
const lastHandler = (normalized: Options): GotReturn => {
// Note: `options` is `undefined` when `new Options(...)` fails
request.options = normalized;
request._noPipe = !normalized?.isStream;
void request.flush();
if (normalized?.isStream) {
return request;
}
promise ||= asPromise(request);
return promise;
};
let iteration = 0;
const iterateHandlers = (newOptions: Options): GotReturn => {
const handler = defaults.handlers[iteration++] ?? lastHandler;
const result = handler(newOptions, iterateHandlers) as GotReturn;
if (is.promise(result) && !request.options?.isStream) {
promise ||= asPromise(request);
if (result !== promise) {
const descriptors = Object.getOwnPropertyDescriptors(promise);
for (const key in descriptors) {
if (key in result) {
// eslint-disable-next-line @typescript-eslint/no-dynamic-delete
delete descriptors[key];
}
}
// eslint-disable-next-line @typescript-eslint/no-floating-promises
Object.defineProperties(result, descriptors);
result.cancel = promise.cancel;
}
}
return result;
};
return iterateHandlers(request.options);
}) as Got;
got.extend = (...instancesOrOptions) => {
const options = new Options(undefined, undefined, defaults.options);
const handlers = [...defaults.handlers];
let mutableDefaults: boolean | undefined;
for (const value of instancesOrOptions) {
if (isGotInstance(value)) {
options.merge(value.defaults.options);
handlers.push(...value.defaults.handlers);
mutableDefaults = value.defaults.mutableDefaults;
} else {
options.merge(value);
if (value.handlers) {
handlers.push(...value.handlers);
}
mutableDefaults = value.mutableDefaults;
}
}
return create({
options,
handlers,
mutableDefaults: Boolean(mutableDefaults),
});
};
// Pagination
const paginateEach = (async function * <T, R>(url: string | URL, options?: OptionsWithPagination<T, R>): AsyncIterableIterator<T> {
let normalizedOptions = new Options(url, options as OptionsInit, defaults.options);
normalizedOptions.resolveBodyOnly = false;
const {pagination} = normalizedOptions;
assert.function(pagination.transform);
assert.function(pagination.shouldContinue);
assert.function(pagination.filter);
assert.function(pagination.paginate);
assert.number(pagination.countLimit);
assert.number(pagination.requestLimit);
assert.number(pagination.backoff);
const allItems: T[] = [];
let {countLimit} = pagination;
let numberOfRequests = 0;
while (numberOfRequests < pagination.requestLimit) {
if (numberOfRequests !== 0) {
// eslint-disable-next-line no-await-in-loop
await delay(pagination.backoff);
}
// eslint-disable-next-line no-await-in-loop
const response = (await got(undefined, undefined, normalizedOptions)) as Response;
// eslint-disable-next-line no-await-in-loop
const parsed: unknown[] = await pagination.transform(response);
const currentItems: T[] = [];
assert.array(parsed);
for (const item of parsed) {
if (pagination.filter({item, currentItems, allItems})) {
if (!pagination.shouldContinue({item, currentItems, allItems})) {
return;
}
yield item as T;
if (pagination.stackAllItems) {
allItems.push(item as T);
}
currentItems.push(item as T);
if (--countLimit <= 0) {
return;
}
}
}
const optionsToMerge = pagination.paginate({
response,
currentItems,
allItems,
});
if (optionsToMerge === false) {
return;
}
if (optionsToMerge === response.request.options) {
normalizedOptions = response.request.options;
} else {
normalizedOptions.merge(optionsToMerge);
assert.any([is.urlInstance, is.undefined], optionsToMerge.url);
if (optionsToMerge.url !== undefined) {
normalizedOptions.prefixUrl = '';
normalizedOptions.url = optionsToMerge.url;
}
}
numberOfRequests++;
}
});
got.paginate = paginateEach as GotPaginate;
got.paginate.all = (async <T, R>(url: string | URL, options?: OptionsWithPagination<T, R>) => {
const results: T[] = [];
for await (const item of paginateEach<T, R>(url, options)) {
results.push(item);
}
return results;
}) as GotPaginate['all'];
// For those who like very descriptive names
got.paginate.each = paginateEach as GotPaginate['each'];
// Stream API
got.stream = ((url: string | URL, options?: StreamOptions) => got(url, {...options, isStream: true})) as GotStream;
// Shortcuts
for (const method of aliases) {
got[method] = ((url: string | URL, options?: Options): GotReturn => got(url, {...options, method})) as GotRequestFunction;
got.stream[method] = ((url: string | URL, options?: StreamOptions) => got(url, {...options, method, isStream: true})) as GotStream;
}
if (!defaults.mutableDefaults) {
Object.freeze(defaults.handlers);
defaults.options.freeze();
}
Object.defineProperty(got, 'defaults', {
value: defaults,
writable: false,
configurable: false,
enumerable: true,
});
return got;
};
export default create;