-
Notifications
You must be signed in to change notification settings - Fork 2k
/
InMemoryLRUCache.ts
47 lines (42 loc) 路 1.19 KB
/
InMemoryLRUCache.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
import LRU from 'lru-cache';
import { KeyValueCache } from './KeyValueCache';
function defaultLengthCalculation(item: any) {
if (Array.isArray(item) || typeof item === 'string') {
return item.length;
}
// Go with the lru-cache default "naive" size, in lieu anything better:
// https://github.com/isaacs/node-lru-cache/blob/a71be6cd/index.js#L17
return 1;
}
export class InMemoryLRUCache<V = string> implements KeyValueCache<V> {
private store: LRU.Cache<string, V>;
// FIXME: Define reasonable default max size of the cache
constructor({
maxSize = Infinity,
length = defaultLengthCalculation,
dispose,
}: {
maxSize?: number;
length?: (value: V, key: string) => number;
dispose?: (key: string, value: V) => any;
} = {}) {
this.store = new LRU({
max: maxSize,
length,
dispose,
});
}
async get(key: string) {
return this.store.get(key);
}
async set(key: string, value: V, options?: { ttl?: number }) {
const maxAge = options && options.ttl && options.ttl * 1000;
this.store.set(key, value, maxAge);
}
async delete(key: string) {
this.store.del(key);
}
async flush(): Promise<void> {
this.store.reset();
}
}