soccer-go
Version:
Soccer CLI for stats and results.
47 lines (46 loc) • 1.71 kB
JavaScript
;
var __importDefault = (this && this.__importDefault) || function (mod) {
return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.cachedApiCall = cachedApiCall;
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 fetch(url, {
headers: { 'X-Auth-Token': authToken ?? '' },
});
if (!response.ok) {
const error = (await response.json().catch(() => ({ message: '' })));
switch (response.status) {
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 = (await response.json());
cache.add(url, data);
return data;
}
process.on('exit', () => {
if (cache) {
cache.persist();
}
});