UNPKG

@villedemontreal/jwt-validator

Version:
102 lines 3.43 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.cachedPublicKeyRepository = exports.CachedPublicKeyRepository = void 0; const src_1 = require("@villedemontreal/general-utils/dist/src"); const lodash_1 = require("lodash"); const luxon_1 = require("luxon"); const configs_1 = require("../config/configs"); const logger_1 = require("../utils/logger"); const publicKeyRepository_1 = require("./publicKeyRepository"); const logger = (0, logger_1.createLogger)('CachedPublicKeyRepository'); class CachedPublicKeyRepository { constructor() { /** * Cached public keys */ this._cachedKeys = {}; } /** * Clears the public keys in cache */ clearCache() { this._cachedKeys = {}; this._nextUpdate = luxon_1.DateTime.utc(); } /** * Return the last public keys * @return {Promise<IPublicKeys>} */ async getAll() { if (!this.isValidCache()) { const keysList = await publicKeyRepository_1.publicKeyRepository.getAll(); if (keysList) { this.updateNextCacheUpdate(); this._cachedKeys = (0, lodash_1.extend)(this._cachedKeys, keysList); } } return this._cachedKeys; } /** * Return one public key * @param {number} keyId * @return {Promise<IPublicKey>} */ async getOne(keyId) { if (!this._cachedKeys[keyId] || !this.isValidCache()) { // In case of network error while getting key, return the cached one try { const key = await publicKeyRepository_1.publicKeyRepository.getOne(keyId); if (key) { this.updateNextCacheUpdate(); this._cachedKeys[keyId] = key; } } catch (err) { if (!this._cachedKeys[keyId] || !this.isTransientError(err)) { throw err; } logger.error(JSON.stringify(err), `[getOne] There was an error getting key ${keyId}, cached value was sent as result`); } } return this._cachedKeys[keyId]; } /** * Check if the error is a network error, server error or * If true, do not throw error * @return {boolean} */ isTransientError(err) { if (err instanceof src_1.ApiErrorAndInfo) { if (err.httpStatus >= 500 || err.httpStatus === 429) return true; return false; } // No status on a superagent network error if (!err.status) return true; const errStatus = +err.status; if (errStatus >= 500 || errStatus === 429) return true; return false; } /** * Check if the cache is stil valid * @return {boolean} */ isValidCache() { if (!this._nextUpdate || luxon_1.DateTime.utc() >= this._nextUpdate) { return false; } return true; } /** * Update the date of the next update * @return */ updateNextCacheUpdate() { this._nextUpdate = luxon_1.DateTime.utc().plus({ seconds: configs_1.configs.getCacheDuration() }); } } exports.CachedPublicKeyRepository = CachedPublicKeyRepository; exports.cachedPublicKeyRepository = new CachedPublicKeyRepository(); //# sourceMappingURL=cachedPublicKeyRepository.js.map