sprcl
Version:
Simple API client for Clash of Clans, Clash Royale, and Brawl Stars
54 lines (45 loc) • 1.65 kB
JavaScript
const https = require('https');
class Connector {
constructor(apiToken, game = 'clashofclans') {
this.apiToken = apiToken;
const hosts = {
clashofclans: 'api.clashofclans.com',
clashroyale: 'api.clashroyale.com',
brawlstars: 'api.brawlstars.com'
};
if (!hosts[game]) throw new Error(`[!] Game "${game}" not supported`);
this.api = hosts[game];
}
async request(args = [], queries = {}) {
const path = '/v1/' + Connector.pack(args).join('/') +
(Object.keys(queries).length ? '?' + new URLSearchParams(queries).toString() : '');
const options = {
hostname: this.api,
path,
method: 'GET',
headers: {
Accept: 'application/json',
Authorization: 'Bearer ' + this.apiToken
}
};
return new Promise((resolve, reject) => {
https.get(options, response => {
let content = [];
response.on('data', chunk => content.push(chunk.toString()));
response.on('end', () => {
const result = JSON.parse(content.join(''));
resolve(Connector.catchAPIError(result));
});
}).on('error', reject);
});
}
static pack(value) {
return Array.isArray(value) ? value : [value];
}
static catchAPIError(json) {
if (json.reason === "accessDenied") json.errorCode = 403;
if (json.reason === "notFound") json.errorCode = 404;
return json;
}
}
module.exports = { Connector };