-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequestManager.js
98 lines (87 loc) · 3.69 KB
/
requestManager.js
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
const zlib = require('zlib');
const http = require('http');
const https = require('https');
/**
* Internal function
* @param {string} method CONNECT, DELETE, GET, HEAD, OPTIONS, PATCH, POST, PUT, TRACE
* @param {string} url
* @param {object} data
* @returns
*/
async function request(method = 'GET', token, url, data = {}, maxBytes = 0, returnData = true) {
return new Promise((resolve, reject) => {
try {
const urlData = new URL(url);
const protocol = urlData.protocol === 'http:' ? http : https;
let downloadedSize = 0;
const options = {
hostname: urlData.hostname,
port: urlData.port || (urlData.protocol === 'https:' ? 443 : 80),
path: urlData.pathname + (urlData.search || ''),
method: method,
rejectUnauthorized: false,
secureProtocol: 'TLSv1_2_method',
headers: {
'Accept-Encoding': 'gzip, deflate, br',
...token ? { 'Authorization': token } : {},
'Content-Type': 'application/json',
...maxBytes > 0 ? { 'Range': `bytes=0-${maxBytes}` } : {}
},
};
const req = protocol.request(options, (res) => {
let stream = res;
if (res.headers['content-encoding'] === 'gzip') {
stream = res.pipe(zlib.createGunzip());
} else if (res.headers['content-encoding'] === 'deflate') {
stream = res.pipe(zlib.createInflate());
} else if (res.headers['content-encoding'] === 'br') {
stream = res.pipe(zlib.createBrotliDecompress());
}
if (returnData && maxBytes === 0) {
let response = [];
stream.on('data', (chunk) => {
response.push(chunk);
});
stream.on('end', () => {
const buffer = Buffer.concat(response);
try {
const data = JSON.parse(buffer.toString());
resolve({ req, res, data });
} catch (error) {
resolve({ req, res, data: buffer.toString() });
}
});
} else if (maxBytes > 0) {
let response = [];
stream.on('data', (chunk) => {
downloadedSize += chunk.length;
if (downloadedSize > maxBytes) {
req.destroy();
resolve({ req, res, data: Buffer.concat(response) });
} else {
response.push(chunk);
}
});
stream.on('end', () => {
resolve({ req, res, data: Buffer.concat(response) });
});
} else {
res.on('data', () => { });
resolve({ req, res });
}
});
req.on('error', (error) => {
reject(error);
});
if (!['GET', 'DELETE'].includes(method) && data) {
const postData = JSON.stringify(data);
options.headers['Content-Length'] = Buffer.byteLength(postData);
req.write(postData);
}
req.end();
} catch (error) {
reject(error);
}
});
};
module.exports = request;