-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest.js
More file actions
76 lines (69 loc) · 2.15 KB
/
Copy pathrequest.js
File metadata and controls
76 lines (69 loc) · 2.15 KB
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
import { URL } from 'url';
import http from 'http';
/**
* @typedef {object} RequestOptions
* @property {string} [pathname="/"]
* @property {string} [address=""]
* @property {Record<string, string>} [headers={}]
* @property {string} [method="GET"]
* @property {boolean} [json=false]
*/
/**
* @template T
* @param {RequestOptions} options
* @param {T} [payload] Required for POST/PUT/DELETE
* @returns {Promise<{ headers: import('http').IncomingHttpHeaders, body: T}>}
*/
export const request = (
{
pathname = '/',
address = '',
headers = {},
method = 'GET',
json = false,
} = {},
payload,
) =>
new Promise((resolve, reject) => {
const url = new URL(pathname, address);
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
headers = Object.assign(headers, {
'Content-Type': 'application/x-www-form-urlencoded',
// @ts-expect-error It's fine
'Content-Length': Buffer.byteLength(payload),
});
}
// This is done to support node 8. From node 10 .request can take
// both an URL object and options object as arguments
const options = {
protocol: url.protocol,
host: url.hostname,
port: url.port,
path: url.pathname + url.search,
headers,
method,
};
const req = http
.request(options, (res) => {
const chunks = [];
res.on('data', (chunk) => {
chunks.push(chunk);
});
res.on('end', () => {
const body = json
? JSON.parse(chunks.join(''))
: chunks.join('');
resolve({
headers: res.headers,
body,
});
});
})
.on('error', (error) => {
reject(error);
});
if (method === 'POST' || method === 'PUT' || method === 'DELETE') {
req.write(payload);
}
req.end();
});