forked from greatestview/homebridge-valetudo-xiaomi-vacuum
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrequest.js
62 lines (52 loc) · 1.56 KB
/
request.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
const http = require('http');
const urllib = require('url');
async function sendJSONRequest(params) {
return new Promise((resolve, reject) => {
if (!params.url) {
reject(Error('Request URL missing'));
}
const components = new urllib.URL(params.url);
const options = {
method: params.method || 'GET',
raw_response: params.raw_response || false,
host: components.hostname,
port: components.port,
path: components.pathname + (components.search ? components.search : ''),
protocol: components.protocol,
headers: { 'Content-Type': 'application/json' },
};
if (params.authentication) {
const credentials = Buffer.from(params.authentication).toString('base64');
options.headers.Authorization = `Basic ${credentials}`;
}
const req = http.request(options, (res) => {
res.setEncoding('utf8');
let chunks = '';
res.on('data', (chunk) => { chunks += chunk; });
res.on('end', () => {
try {
if (params.log) {
params.log.debug(`Raw response: ${chunks}`);
}
if (options.raw_response) {
resolve(chunks);
} else {
const parsed = JSON.parse(chunks);
resolve(parsed);
}
} catch (e) {
reject(e);
}
});
});
req.on('error', (err) => {
reject(err);
});
if (params.content) {
const stringified = JSON.stringify(params.content);
req.write(stringified);
}
req.end();
});
}
module.exports = { sendJSONRequest };