-
Notifications
You must be signed in to change notification settings - Fork 10
Expand file tree
/
Copy pathcache.ts
More file actions
42 lines (37 loc) · 1.05 KB
/
cache.ts
File metadata and controls
42 lines (37 loc) · 1.05 KB
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
import { handleGrpcResult } from "./utils/grpcHelpers.js";
import JSONbig from "json-bigint";
JSONbig({ useNativeBigInt: true });
class Cache<T> {
limit: number;
cache: Map<string, T>;
constructor(limit: number) {
this.limit = limit;
this.cache = new Map();
}
set(key: string, value: T) {
if (this.cache.size >= this.limit) {
const firstItemKey = this.cache.keys().next().value!;
this.cache.delete(firstItemKey);
}
this.cache.set(key, value);
}
async get(
func: (args: any) => Promise<T> | AsyncIterable<T>,
args: any,
): Promise<T | T[]> {
const cache_key = JSON.stringify(args);
if (this.cache.has(cache_key)) {
const temp = this.cache.get(cache_key)!;
this.cache.delete(cache_key);
this.cache.set(cache_key, temp);
return temp;
}
const result = await handleGrpcResult(func(args));
this.set(cache_key, result as any);
return result;
}
}
const cache = new Cache<any>(
+(process.env.TARI_EXPLORER_OLD_BLOCKS_CACHE_SETTINGS || 1000),
);
export default cache;