node-brawlstars
Version:
Javascript library to communicate with BrawlStars API
63 lines (62 loc) • 2.68 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.BrawlClient = void 0;
const axios_1 = require("axios");
const utils_1 = require("./utils");
const models_1 = require("./models");
const exceptions_1 = require("./exceptions");
class BrawlClient extends axios_1.Axios {
constructor(token) {
super({
baseURL: 'https://api.brawlstars.com/v1',
headers: {
Authorization: `Bearer ${token}`,
'User-Agent': 'node-brawlstars https://github.com/SocketSomeone/node-brawlstars',
'Content-Type': 'application/json'
}
});
this.cache = new Map();
this.errorFactory = (status, message) => new exceptions_1.ExceptionByCode[status](message);
}
async fetch(url, query = {}) {
let response;
if (this.cache.has(url)) {
response = this.cache.get(url);
}
else {
response = await this.get(url, { params: query });
this.cache.set(url, response);
const cache = response.headers['cache-control'];
const maxAge = parseInt(cache.match(/max-age=(\d+)/)?.[1]) ?? 0;
setTimeout(() => this.cache.delete(url), maxAge * 1000);
}
if (response.status !== 200)
throw this.errorFactory(response.status, response.data);
return JSON.parse(response.data);
}
getClub(tag) {
return this.fetch(`/clubs/${utils_1.TagUtils.Clean(tag)}`).then(raw => models_1.Club.FromRaw(this, raw));
}
getClubMembers(tag, options) {
return this.fetch(`/clubs/${utils_1.TagUtils.Clean(tag)}/members`, options).then(raw => ({ items: raw.items.map(raw => models_1.Club.Member.FromRaw(raw)), cursor: raw.cursor }));
}
getPlayer(tag) {
return this.fetch(`/players/${utils_1.TagUtils.Clean(tag)}`).then(raw => models_1.Player.FromRaw(this, raw));
}
getPlayerBattlelog(tag, options) {
return this.fetch(`/players/${utils_1.TagUtils.Clean(tag)}/battlelog`, options).then(raw => ({ items: raw.items.map(raw => models_1.Battle.FromRaw(this, raw)), cursor: raw.cursor }));
}
getBrawlers(options) {
return this.fetch('/brawlers', options).then(raw => ({
items: raw.items.map(raw => models_1.Brawler.FromRaw(this, raw)),
cursor: raw.cursor
}));
}
getBrawler(id) {
return this.fetch(`/brawlers/${id}`).then(raw => models_1.Brawler.FromRaw(this, raw));
}
getEventRotation() {
return this.fetch('/events/rotation').then(raw => models_1.ScheduledEvent.FromRaw(raw));
}
}
exports.BrawlClient = BrawlClient;