-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
63 lines (54 loc) · 1.73 KB
/
index.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
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
import { createHash } from "crypto";
import { LRUCache } from "lru-cache";
import { QueryResultCache } from "typeorm/cache/QueryResultCache";
import { QueryResultCacheOptions } from "typeorm/cache/QueryResultCacheOptions";
export default class LRUCacheProvider<FC> implements QueryResultCache {
private cache: LRUCache<string, QueryResultCacheOptions, FC>;
constructor(options: LRUCache.Options<string, QueryResultCacheOptions, FC>) {
this.cache = new LRUCache<string, QueryResultCacheOptions, FC>(options);
}
private makeIdentifier(query?: string): string {
return query ? `${createHash("md5").update(query).digest("hex")}` : "";
}
connect(): Promise<void> {
return Promise.resolve();
}
disconnect(): Promise<void> {
return Promise.resolve();
}
synchronize(): Promise<void> {
return Promise.resolve();
}
async getFromCache(
options: QueryResultCacheOptions
): Promise<QueryResultCacheOptions | undefined> {
const value = this.cache.get(
options.identifier || this.makeIdentifier(options.query)
);
return Promise.resolve(value);
}
async storeInCache(
options: QueryResultCacheOptions,
savedCache: QueryResultCacheOptions | undefined
): Promise<void> {
this.cache.set(
options.identifier || this.makeIdentifier(options.query),
options,
{
start: options.time,
ttl: options.duration,
}
);
}
isExpired(savedCache: QueryResultCacheOptions): boolean {
return savedCache.time! + savedCache.duration < new Date().getTime();
}
async clear(): Promise<void> {
this.cache.clear();
}
async remove(identifiers: string[]): Promise<void> {
for (const identifier of identifiers) {
this.cache.delete(identifier);
}
}
}