node-artifact-api
Version:
A node module wrapper for the Valve official Artifact API
83 lines (82 loc) • 3.47 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : new P(function (resolve) { resolve(result.value); }).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_fetch_1 = require("node-fetch");
const constants_1 = require("../helpers/constants");
class CardApi {
constructor(cache) {
this.API_ROOT = 'https://playartifact.com/cardset/';
this.CACHE = cache;
}
getCard(cardId, searchSets, clearCache = false) {
return __awaiter(this, void 0, void 0, function* () {
return new Promise((resolve, reject) => {
let cacheCard = this.CACHE.getCacheCard(cardId, clearCache);
if (cacheCard) {
resolve(cacheCard);
}
const setArray = searchSets || constants_1.SET_IDS;
const setArrayPromises = setArray.map((setId) => {
return this.getSet(setId, clearCache);
});
Promise.all(setArrayPromises)
.then(() => {
cacheCard = this.CACHE.getCacheCard(cardId);
if (cacheCard) {
resolve(cacheCard);
}
else {
reject('Invalid Card ID');
}
})
.catch(() => {
reject('Invalid Card ID');
});
});
});
}
getSet(setId, clearCache = false) {
return __awaiter(this, void 0, void 0, function* () {
try {
const cacheSet = this.CACHE.getCacheSet(setId, clearCache);
if (!!cacheSet) {
return {
card_set: cacheSet,
};
}
const preflightUrl = `${this.API_ROOT}${setId}`;
const preflight = yield this._fetchPreflight(preflightUrl);
const cardUrl = `${preflight.cdn_root}${preflight.url.substring(1, preflight.url.length)}`;
const cardset = yield node_fetch_1.default(cardUrl);
const cardsetJson = yield cardset.json();
this.CACHE.setCacheSet(setId, preflight, cardsetJson.card_set);
return cardsetJson;
}
catch (error) {
console.log(error);
throw Error(`Error while fetching card: ${JSON.stringify(error)}`);
}
});
}
_fetchPreflight(url) {
return __awaiter(this, void 0, void 0, function* () {
try {
const prefetch = yield node_fetch_1.default(url);
const json = prefetch.json();
return json;
}
catch (error) {
console.log(error);
throw Error(`Error while fetching preflight: ${JSON.stringify(error)}`);
}
});
}
}
exports.CardApi = CardApi;