-
Notifications
You must be signed in to change notification settings - Fork 0
/
helper.js
93 lines (86 loc) · 2.54 KB
/
helper.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
const https = require('https')
const { brotliDecompress } = require('zlib')
/**
*
* @param {Buffer} data
*/
const decodeBrotli = (data) => {
return new Promise((resolve, reject) => {
brotliDecompress(data, (err, res) => {
err ? reject(err) : resolve(res);
})
})
}
/**
* @param {String} data JSON stringifyed data
* @returns {Promise}
*/
const sendJSONPost = (data, host, path, port) => {
return new Promise((resolve, reject) => {
const req = https.request({
host,
path,
port,
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Content-Length': Buffer.byteLength(data),
'User-Agent': 'NodeJS/12.0',
'Accept': '*/*',
'Host': 'uwatch.live',
'Accept-Encoding': 'gzip, deflate, br',
'Connection': 'keep-alive'
}
}, async (res) => {
const encoding = res.headers['content-encoding'] ? res.headers['content-encoding'] : 'none';
const isJson = res.headers['content-type'] && res.headers['content-type'].indexOf('application/json') !== -1 ? true : false;
const data = await retrieveResponseData(res, encoding, isJson);
resolve(data);
});
req.on('error', (err) => {
reject(err)
})
req.write(data);
req.end();
})
}
/**
*
* @param {ReadStream} stream
* @param {String} encoding
*/
const retrieveResponseData = (stream, encoding, isJson) => {
return new Promise(async (resolve, reject) => {
const body = [];
stream.on('data', (chunk) => {
body.push(chunk);
})
stream.on('end', async () => {
let dataString;
switch (encoding) {
case 'br':
dataString = await decodeBrotli(Buffer.concat(body));
break ;
default:
dataString = body.join('');
}
if (!dataString.length) {
resolve(null);
} else {
if(!isJson){
resolve(dataString)
} else {
try {
resolve(JSON.parse(dataString));
} catch(e) {
reject('POST body parse error' + e);
}
}
}
})
})
}
module.exports = {
sendJSONPost,
retrieveResponseData
}