-
Notifications
You must be signed in to change notification settings - Fork 1
/
net.js
62 lines (53 loc) · 1.73 KB
/
net.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
'use strict';
const http = require('http');
const https = require('https');
/**
* Send a request to the given endpoint
* @param {string} endpoint - The URL to send the request to
* @param {string} method - The HTTP method to use
* @param {string} body - The body of the request
* @returns {Promise<string>} The response
*/
const request = async (endpoint, method, body) => {
const url = new URL(endpoint);
const opts = {
'auth': url.username + ':' + url.password,
'host': url.host,
'hostname': url.hostname,
'port': url.port,
'href': url.href,
'protocol': url.protocol,
'path': url.pathname + url.search,
'method': method
};
const server = opts.protocol === 'https:' ? https : http;
return new Promise((resolve, reject) => {
const req = server.request(opts, (res) => {
let strData = '';
res.setEncoding('utf8');
res.on('data', d => strData += d);
res.on('end', () => {
// Return the full string
if(res.statusCode === 200) {
resolve(strData);
}
else {
reject(strData ? strData : res);
}
});
});
req.on('error', error => reject(error));
req.setHeader('User-Agent', 'btc-rpc-client');
if (body) req.write(body);
req.end();
});
};
/**
* Alias to {@link request} with POST method and body
* @param {string} endpoint - The URL to send the request to
* @param {any} body - The body of the request
* @returns {Promise<string>} The response
*/
exports.post = async (endpoint, body) => {
return await request(endpoint, 'POST', body);
};