UNPKG

@launchdarkly/js-server-sdk-common

Version:
84 lines 2.38 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function isStale(record) { return Date.now() > record.expiration; } /** * A basic TTL cache with configurable TTL and check interval. */ class TtlCache { constructor(_options) { this._options = _options; this._storage = new Map(); this._checkIntervalHandle = setInterval(() => { this._purgeStale(); }, _options.checkInterval * 1000); } /** * Get a value from the cache. * @param key The key to get a value for. * @returns The value for the key, or undefined if the key was not added, or * if the value has expired. */ get(key) { const record = this._storage.get(key); if (record && isStale(record)) { this._storage.delete(key); return undefined; } return record === null || record === void 0 ? void 0 : record.value; } /** * Set an item in the cache. It will expire after the TTL specified * in the cache configuration. * @param key The key for the value. * @param value The value to set. */ set(key, value) { this._storage.set(key, { value, expiration: Date.now() + this._options.ttl * 1000, }); } /** * Delete the item with the specific key. If the item does not exist, * then there will be no change to the cache. * @param key The key of the value to delete. */ delete(key) { this._storage.delete(key); } /** * Clear the items that are in the cache. */ clear() { this._storage.clear(); } /** * Indicate that you are no longer going to use the cache. The cache will be * cleared and it will stop checking for stale items. */ close() { this.clear(); if (this._checkIntervalHandle) { clearInterval(this._checkIntervalHandle); this._checkIntervalHandle = null; } } _purgeStale() { this._storage.forEach((record, key) => { if (isStale(record)) { this._storage.delete(key); } }); } /** * This is for testing. * @internal */ get size() { return this._storage.size; } } exports.default = TtlCache; //# sourceMappingURL=TtlCache.js.map