-
Notifications
You must be signed in to change notification settings - Fork 0
/
requester.js
69 lines (52 loc) · 1.45 KB
/
requester.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
const https = require('https');
const { parse } = require('url');
const API_ENDPOINT = 'https://union.serux.pro/api/';
const ENDPOINTS = {
Message: 'server/:id/messages'
};
const defaultHeaders = {
'User-Agent': 'UnionBot/1.0 (union.js, https://github.com/Union-Chat/union.js)',
'Content-Type': 'application/json'
};
function getRoute (route, id) {
return ENDPOINTS[route].replace(':id', id);
}
function request (method, endpoint, headers, data) {
return new Promise((resolve, reject) => {
const route = parse(API_ENDPOINT + endpoint);
const { hostname, path } = route;
headers = Object.assign(headers, defaultHeaders);
const opts = {
method,
hostname,
path,
headers
};
const req = https.request(opts, (res) => {
const chunks = [];
res.on('data', chunks.push.bind(chunks));
res.on('end', () => {
const concatenated = jsonSafeParse(Buffer.concat(chunks).toString());
if (res.statusCode !== 200) {
reject(concatenated, res.statusCode);
} else {
resolve(concatenated);
}
});
}).on('error', reject);
req.end(JSON.stringify(data));
});
}
function jsonSafeParse (data) {
try {
return JSON.parse(data);
} catch (_) {
return data;
}
}
module.exports = {
ENDPOINTS,
get: request.bind(null, 'GET'),
post: request.bind(null, 'POST'),
getRoute
};