Openstatus
www.openstatus.dev
1// Props to https://github.com/isaacs/node-lru-cache?tab=readme-ov-file#storage-bounds-safety
2
3export class MemoryCache {
4 private ttl: number;
5 private data: Map<string, unknown>;
6 private timers: Map<string, NodeJS.Timeout>;
7
8 constructor(defaultTTL = 60 * 1000) {
9 this.ttl = defaultTTL;
10 this.data = new Map();
11 this.timers = new Map();
12 }
13
14 set<T>(key: string, value: T, ttl = this.ttl) {
15 if (this.timers.has(key)) {
16 clearTimeout(this.timers.get(key));
17 }
18 this.timers.set(
19 key,
20 setTimeout(() => this.delete(key), ttl),
21 );
22 this.data.set(key, value);
23 return value;
24 }
25
26 get<T>(key: string) {
27 return this.data.get(key) as T;
28 }
29
30 has(key: string) {
31 return this.data.has(key);
32 }
33
34 delete(key: string) {
35 if (this.timers.has(key)) {
36 clearTimeout(this.timers.get(key));
37 }
38 this.timers.delete(key);
39 return this.data.delete(key);
40 }
41
42 clear() {
43 this.data.clear();
44 for (const timer of Array.from(this.timers.values())) {
45 clearTimeout(timer);
46 }
47 this.timers.clear();
48 }
49}
50
51const _cache = new MemoryCache();