@graphql-mesh/cache-inmemory-lru
Version:
53 lines (52 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
const utils_1 = require("@graphql-mesh/utils");
const disposablestack_1 = require("@whatwg-node/disposablestack");
class InMemoryLRUCache {
constructor(options) {
this.timeouts = new Set();
this.lru = (0, utils_1.createLruCache)(options?.max, options?.ttl);
const subId = options?.pubsub?.subscribe?.('destroy', () => {
options?.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(timeout);
this.lru.delete(key);
}, options.ttl * 1000);
this.timeouts.add(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]() {
for (const timeout of this.timeouts) {
clearTimeout(timeout);
this.timeouts.delete(timeout);
}
}
}
exports.default = InMemoryLRUCache;