-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.mjs
65 lines (54 loc) · 1.7 KB
/
utils.mjs
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
import { PassThrough } from "stream";
import { request as httpsRequest } from "https";
// ===================================================================
export const createReadableCopies = (n, readable) => {
return Array.from({ length: n }, () => readable.pipe(new PassThrough()));
};
// -------------------------------------------------------------------
export const fromCallback = (fn) =>
new Promise((resolve, reject) => {
fn((error, result) => (error ? reject(error) : resolve(result)));
});
// -------------------------------------------------------------------
export const proxyHttpsRequest = (
{ headers, hostname, method, url, port },
inputReq
) =>
new Promise((resolve, reject) => {
const req = httpsRequest(
{
headers: headers || inputReq.headers,
hostname,
method: method || inputReq.method,
path: url || inputReq.url,
port,
rejectUnauthorized: false,
},
resolve
).on("error", reject);
inputReq.pipe(req);
});
// -------------------------------------------------------------------
const _isPort = (value) =>
typeof value === "number" &&
value >= 0 &&
value <= 65534 &&
Math.floor(value) === value;
// splitHost('localhost:80') => { hostname: 'localhost', port: 80 }
// splitHost('localhost') => { hostname: 'localhost' }
// splitHost('80') => { port: 80 }
export const splitHost = (host) => {
host = String(host);
const i = host.lastIndexOf(":");
if (i === -1) {
const port = +host;
return _isPort(port) ? { port } : { hostname: host };
}
const port = +host.slice(i + 1);
return _isPort(port)
? {
hostname: host.slice(0, i),
port,
}
: { hostname: host };
};