-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathindex.ts
371 lines (329 loc) · 10.4 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
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
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
/**
* @license
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {Agent, AgentOptions as HttpsAgentOptions} from 'https';
import {AgentOptions as HttpAgentOptions} from 'http';
import type * as f from 'node-fetch' with {'resolution-mode': 'import'};
import {PassThrough, Readable, pipeline} from 'stream';
import {getAgent} from './agents';
import {TeenyStatistics} from './TeenyStatistics';
import {randomUUID} from 'crypto';
// eslint-disable-next-line @typescript-eslint/no-var-requires
const streamEvents = require('stream-events');
import type nodeFetch from 'node-fetch' with {'resolution-mode': 'import'};
const fetch = (...args: Parameters<typeof nodeFetch>) =>
import('node-fetch').then(({default: fetch}) => fetch(...args));
export interface CoreOptions {
method?: string;
timeout?: number;
gzip?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
json?: any;
headers?: Headers;
body?: string | {};
useQuerystring?: boolean;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
qs?: any;
proxy?: string;
multipart?: RequestPart[];
forever?: boolean;
pool?: HttpsAgentOptions | HttpAgentOptions;
}
export interface OptionsWithUri extends CoreOptions {
uri: string;
}
export interface OptionsWithUrl extends CoreOptions {
url: string;
}
export type Options = OptionsWithUri | OptionsWithUrl;
export interface Request extends PassThrough {
agent: Agent | false;
headers: Headers;
href?: string;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface Response<T = any> {
statusCode: number;
headers: Headers;
body: T;
request: Request;
statusMessage?: string;
}
export interface RequestPart {
body: string | Readable;
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
export interface RequestCallback<T = any> {
(err: Error | null, response: Response, body?: T): void;
}
export class RequestError extends Error {
code?: number;
}
interface Headers {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[index: string]: any;
}
/**
* Convert options from Request to Fetch format
* @private
* @param reqOpts Request options
*/
function requestToFetchOptions(reqOpts: Options) {
const options: f.RequestInit = {
method: reqOpts.method || 'GET',
...(reqOpts.timeout && {timeout: reqOpts.timeout}),
...(typeof reqOpts.gzip === 'boolean' && {compress: reqOpts.gzip}),
};
if (typeof reqOpts.json === 'object') {
// Add Content-type: application/json header
reqOpts.headers = reqOpts.headers || {};
reqOpts.headers['Content-Type'] = 'application/json';
// Set body to JSON representation of value
options.body = JSON.stringify(reqOpts.json);
} else {
if (Buffer.isBuffer(reqOpts.body)) {
options.body = reqOpts.body;
} else if (typeof reqOpts.body !== 'string') {
options.body = JSON.stringify(reqOpts.body);
} else {
options.body = reqOpts.body;
}
}
// eslint-disable-next-line @typescript-eslint/no-explicit-any
options.headers = reqOpts.headers as any;
let uri = ((reqOpts as OptionsWithUri).uri ||
(reqOpts as OptionsWithUrl).url) as string;
if (!uri) {
throw new Error('Missing uri or url in reqOpts.');
}
if (reqOpts.useQuerystring === true || typeof reqOpts.qs === 'object') {
// eslint-disable-next-line @typescript-eslint/no-var-requires
const qs = require('querystring');
const params = qs.stringify(reqOpts.qs);
uri = uri + '?' + params;
}
options.agent = getAgent(uri, reqOpts);
return {uri, options};
}
/**
* Convert a response from `fetch` to `request` format.
* @private
* @param opts The `request` options used to create the request.
* @param res The Fetch response
* @returns A `request` response object
*/
function fetchToRequestResponse(opts: f.RequestInit, res: f.Response) {
const request = {} as Request;
request.agent = (opts.agent as Agent) || false;
request.headers = (opts.headers || {}) as Headers;
request.href = res.url;
// headers need to be converted from a map to an obj
const resHeaders = {} as Headers;
res.headers.forEach((value, key) => (resHeaders[key] = value));
const response = Object.assign(res.body as {}, {
statusCode: res.status,
statusMessage: res.statusText,
request,
body: res.body,
headers: resHeaders,
toJSON: () => ({headers: resHeaders}),
});
return response as Response;
}
/**
* Create POST body from two parts as multipart/related content-type
* @private
* @param boundary
* @param multipart
*/
function createMultipartStream(boundary: string, multipart: RequestPart[]) {
const finale = `--${boundary}--`;
const stream: PassThrough = new PassThrough();
for (const part of multipart) {
const preamble = `--${boundary}\r\nContent-Type: ${
(part as {['Content-Type']?: string})['Content-Type']
}\r\n\r\n`;
stream.write(preamble);
if (typeof part.body === 'string') {
stream.write(part.body);
stream.write('\r\n');
} else {
part.body.pipe(stream, {end: false});
part.body.on('end', () => {
stream.write('\r\n');
stream.write(finale);
stream.end();
});
}
}
return stream;
}
function teenyRequest(reqOpts: Options): Request;
function teenyRequest(reqOpts: Options, callback: RequestCallback): void;
function teenyRequest(
reqOpts: Options,
callback?: RequestCallback,
): Request | void {
const {uri, options} = requestToFetchOptions(reqOpts);
const multipart = reqOpts.multipart as RequestPart[];
if (reqOpts.multipart && multipart.length === 2) {
if (!callback) {
// TODO: add support for multipart uploads through streaming
throw new Error('Multipart without callback is not implemented.');
}
const boundary: string = randomUUID();
(options.headers as Headers)['Content-Type'] =
`multipart/related; boundary=${boundary}`;
options.body = createMultipartStream(boundary, multipart);
// Multipart upload
teenyRequest.stats.requestStarting();
fetch(uri, options).then(
res => {
teenyRequest.stats.requestFinished();
const header = res.headers.get('content-type');
const response = fetchToRequestResponse(options, res);
const body = response.body;
if (
header === 'application/json' ||
header === 'application/json; charset=utf-8'
) {
res.json().then(
json => {
response.body = json;
callback(null, response, json);
},
(err: Error) => {
callback(err, response, body);
},
);
return;
}
res.text().then(
text => {
response.body = text;
callback(null, response, text);
},
err => {
callback(err, response, body);
},
);
},
err => {
teenyRequest.stats.requestFinished();
callback(err, null!, null);
},
);
return;
}
if (callback === undefined) {
// Stream mode
const requestStream = streamEvents(new PassThrough());
// eslint-disable-next-line @typescript-eslint/no-explicit-any
let responseStream: any;
requestStream.once('reading', () => {
if (responseStream) {
pipeline(responseStream, requestStream, () => {});
} else {
requestStream.once('response', () => {
pipeline(responseStream, requestStream, () => {});
});
}
});
options.compress = false;
teenyRequest.stats.requestStarting();
fetch(uri, options).then(
res => {
teenyRequest.stats.requestFinished();
responseStream = res.body;
responseStream.on('error', (err: Error) => {
requestStream.emit('error', err);
});
const response = fetchToRequestResponse(options, res);
requestStream.emit('response', response);
},
err => {
teenyRequest.stats.requestFinished();
requestStream.emit('error', err);
},
);
// fetch doesn't supply the raw HTTP stream, instead it
// returns a PassThrough piped from the HTTP response
// stream.
return requestStream as Request;
}
// GET or POST with callback
teenyRequest.stats.requestStarting();
fetch(uri, options).then(
res => {
teenyRequest.stats.requestFinished();
const header = res.headers.get('content-type');
const response = fetchToRequestResponse(options, res);
const body = response.body;
if (
header === 'application/json' ||
header === 'application/json; charset=utf-8'
) {
if (response.statusCode === 204) {
// Probably a DELETE
callback(null, response, body);
return;
}
res.json().then(
json => {
response.body = json;
callback(null, response, json);
},
err => {
callback(err, response, body);
},
);
return;
}
res.text().then(
text => {
const response = fetchToRequestResponse(options, res);
response.body = text;
callback(null, response, text);
},
err => {
callback(err, response, body);
},
);
},
err => {
teenyRequest.stats.requestFinished();
callback(err, null!, null);
},
);
return;
}
teenyRequest.defaults = (defaults: CoreOptions) => {
return (reqOpts: Options, callback?: RequestCallback): Request | void => {
const opts = {...defaults, ...reqOpts};
if (callback === undefined) {
return teenyRequest(opts);
}
teenyRequest(opts, callback);
};
};
/**
* Single instance of an interface for keeping track of things.
*/
teenyRequest.stats = new TeenyStatistics();
teenyRequest.resetStats = (): void => {
teenyRequest.stats = new TeenyStatistics(teenyRequest.stats.getOptions());
};
export {teenyRequest};