UNPKG

soccer-go

Version:

Soccer CLI for stats and results.

51 lines (50 loc) 1.83 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.cachedApiCall = void 0; const phin_1 = __importDefault(require("phin")); const Cache_1 = __importDefault(require("./Cache")); const system_paths_1 = require("../utils/system-paths"); const errors_1 = require("../utils/errors"); const cache = new Cache_1.default((0, system_paths_1.getCacheDir)()); async function cachedApiCall(url, authToken, expiry) { const item = cache.get(url); if (item) { const age = Date.now() - item.date; if (age < expiry) { return item.data; } // data is expired cache.remove(url); } const response = await (0, phin_1.default)({ url, parse: 'json', headers: { 'X-Auth-Token': authToken }, }); if (response.statusCode == null || response.statusCode >= 400) { const error = response.body; switch (response.statusCode) { case 400: if (error.message === 'Your API token is invalid.') { throw new errors_1.ApplicationError(errors_1.ErrorCode.API_KEY_INVALID); } throw new errors_1.ApplicationError(errors_1.ErrorCode.API_RESPONSE_400, error.message); case 429: throw new errors_1.ApplicationError(errors_1.ErrorCode.API_RESPONSE_429); default: throw new errors_1.ApplicationError(errors_1.ErrorCode.API_RESPONSE_500); } } const data = response.body; cache.add(url, data); return data; } exports.cachedApiCall = cachedApiCall; process.on('exit', () => { if (cache) { cache.persist(); } });