|
| 1 | +import stringify from "fast-json-stable-stringify"; |
| 2 | +import BaseLruCache from "lru-cache"; |
| 3 | + |
| 4 | +export type CacheOptions<V> = BaseLruCache.Options<string, V> & { |
| 5 | + name: string; |
| 6 | + fastStringify?: boolean; |
| 7 | +}; |
| 8 | + |
| 9 | +export class LruCache<K, V> { |
| 10 | + private cache!: BaseLruCache<string, V>; |
| 11 | + private stringify: (_: K) => string; |
| 12 | + |
| 13 | + constructor(private options: CacheOptions<V>) { |
| 14 | + this.cache = new BaseLruCache<string, V>({ |
| 15 | + // if using the dispose callback, |
| 16 | + // by default automatically prune expired entries so |
| 17 | + // they are delivered consistently and quickly |
| 18 | + ...(options.dispose || options.disposeAfter |
| 19 | + ? { ttlAutopurge: true } |
| 20 | + : {}), |
| 21 | + ...options, |
| 22 | + dispose: (...args) => { |
| 23 | + options.dispose?.(...args); |
| 24 | + }, |
| 25 | + disposeAfter: (...args) => { |
| 26 | + options.disposeAfter?.(...args); |
| 27 | + }, |
| 28 | + }); |
| 29 | + this.stringify = options.fastStringify ? JSON.stringify : stringify; |
| 30 | + } |
| 31 | + |
| 32 | + public set(key: K, value: V, ttl?: number): void { |
| 33 | + const keyString = this.stringify(key); |
| 34 | + if (!this.cache.set(keyString, value, { ttl })) { |
| 35 | + const size = this.cache.sizeCalculation |
| 36 | + ? this.cache.sizeCalculation(value, keyString) |
| 37 | + : "unknown"; |
| 38 | + throw Error(`Value too large (${size} > ${this.cache.max})`); |
| 39 | + } |
| 40 | + } |
| 41 | + |
| 42 | + public get(key: K): V | undefined { |
| 43 | + const keyString = this.stringify(key); |
| 44 | + return this.cache.get(keyString); |
| 45 | + } |
| 46 | + |
| 47 | + public delete(key: K) { |
| 48 | + this.cache.delete(this.stringify(key)); |
| 49 | + } |
| 50 | + |
| 51 | + public peek(key: K): V | undefined { |
| 52 | + return this.cache.peek(this.stringify(key)); |
| 53 | + } |
| 54 | + |
| 55 | + public size() { |
| 56 | + return this.cache.size; |
| 57 | + } |
| 58 | + |
| 59 | + public clear() { |
| 60 | + this.cache.clear(); |
| 61 | + } |
| 62 | + |
| 63 | + public forEach(callback: (value: V) => void) { |
| 64 | + this.cache.forEach(callback); |
| 65 | + } |
| 66 | + |
| 67 | + public purgeStale(): boolean { |
| 68 | + return this.cache.purgeStale(); |
| 69 | + } |
| 70 | +} |
0 commit comments