@graphql-mesh/cache-inmemory-lru
Version:
50 lines (49 loc) • 1.46 kB
JavaScript
import { createLruCache } from '@graphql-mesh/utils';
import { DisposableSymbols } from '@whatwg-node/disposablestack';
export default class InMemoryLRUCache {
constructor(options) {
this.timeouts = new Set();
this.lru = createLruCache(options?.max, options?.ttl);
const subId = options?.pubsub?.subscribe?.('destroy', () => {
options?.pubsub?.unsubscribe(subId);
this[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;
}
[DisposableSymbols.dispose]() {
for (const timeout of this.timeouts) {
clearTimeout(timeout);
this.timeouts.delete(timeout);
}
}
}