-
Notifications
You must be signed in to change notification settings - Fork 1
/
connector.js
48 lines (43 loc) · 1.44 KB
/
connector.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
const https = require('https');
class Connector {
constructor(apiToken) {
this.api = 'api.clashroyale.com';
this.apiToken = apiToken;
}
async request(args = [], queries = {}) {
const options = {
hostname: this.api,
path: '/v1/' + Connector.pack(args).join('/') + (queries.length === 0 ? '' : '?' +
Object.keys(queries).map(key => `${key}=${queries[key]}`).join('&')),
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + this.apiToken
}
};
return new Promise((resolve, reject) => {
https.get(options, async response => {
let content = [];
response.on('data', data => {
content.push(data.toString());
});
response.on('end', _ => {
const result = JSON.parse(content.join(''));
resolve(Connector.catchAPIError(result));
});
}).on('error', error => {
reject(error);
})
});
}
static catchAPIError(jsonObject) {
if (jsonObject.reason) {
throw new Error(`API error: ${jsonObject.message}`);
}
return jsonObject;
}
static pack(value) {
return value.constructor.name === 'Array' ? value : [value];
}
}
module.exports = {Connector};