UNPKG

@graphql-mesh/cache-inmemory-lru

Version:
61 lines (60 loc) 2.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const types_1 = require("@graphql-mesh/types"); const utils_1 = require("@graphql-mesh/utils"); const disposablestack_1 = require("@whatwg-node/disposablestack"); class InMemoryLRUCache { constructor(options) { this.timeouts = new Map(); this.lru = (0, utils_1.createLruCache)(options?.max, options?.ttl); const pubsub = (0, types_1.toMeshPubSub)(options?.pubsub); const subId = pubsub?.subscribe?.('destroy', () => { pubsub.unsubscribe(subId); this[disposablestack_1.DisposableSymbols.dispose](); }); } get(key) { return this.lru.get(key); } set(key, value, options) { this.lru.set(key, value); if (options?.ttl && options.ttl > 0) { const timeout = setTimeout(() => { this.timeouts.delete(key); this.lru.delete(key); }, options.ttl * 1000); const existingTimeout = this.timeouts.get(key); if (existingTimeout) { // we debounce the timeout because we dont want to "pull the rug" from a "parallel" get clearTimeout(existingTimeout); } this.timeouts.set(key, timeout); } } delete(key) { try { this.lru.delete(key); return true; } catch (e) { return false; } } getKeysByPrefix(prefix) { const keysWithPrefix = []; for (const key of this.lru.keys()) { if (key.startsWith(prefix)) { keysWithPrefix.push(key); } } return keysWithPrefix; } [disposablestack_1.DisposableSymbols.dispose]() { // clear all timeouts and then empty the map for (const timeout of this.timeouts.values()) { clearTimeout(timeout); } this.timeouts.clear(); } } exports.default = InMemoryLRUCache;