1 | const https = require('https');
|
2 |
|
3 | module.exports = {
|
4 |
|
5 | post: (domain, apiPath, apiKey, sendObj, logStuff) => new Promise((resolve, reject) => {
|
6 | const postData = JSON.stringify(sendObj);
|
7 | const options = {
|
8 | hostname: domain,
|
9 | port: 443,
|
10 | path: apiPath,
|
11 | method: 'POST',
|
12 | headers: {
|
13 | 'Content-Type': 'application/json',
|
14 | 'Content-Length': postData.length,
|
15 | 'Authorization': apiKey
|
16 | }
|
17 | };
|
18 | const req = https.request(options, res => {
|
19 | if (logStuff) {
|
20 | console.log(`BLAPI: posted to ${domain}${apiPath}`);
|
21 | console.log('BLAPI: statusCode:', res.statusCode);
|
22 | console.log('BLAPI: headers:', res.headers);
|
23 | res.on('data', d => {
|
24 | console.log(`BLAPI: data: ${d}`);
|
25 | });
|
26 | }
|
27 | });
|
28 | req.on('error', e => {
|
29 | console.error(`BLAPI: ${e}`);
|
30 | reject(new Error(`Request to ${req.url} failed with Errorcode ${req.status}:\n${req.statusText}`));
|
31 | });
|
32 | req.write(postData);
|
33 | req.end();
|
34 | resolve();
|
35 | }),
|
36 |
|
37 | get: url => new Promise((resolve, reject) => {
|
38 | https.get(url, resp => {
|
39 | let data = '';
|
40 | resp.on('data', chunk => {
|
41 | data += chunk;
|
42 | });
|
43 | resp.on('end', () => {
|
44 | resolve(JSON.parse(data));
|
45 | });
|
46 | resp.on('error', e => {
|
47 | console.error(`BLAPI: ${e}`);
|
48 | reject(new Error(`Request to ${resp.url} failed with Errorcode ${resp.status}:\n${resp.statusText}`));
|
49 | });
|
50 | });
|
51 | })
|
52 | };
|