-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathinmemoryCache.ts
48 lines (40 loc) · 1.21 KB
/
inmemoryCache.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
/**
* In-memory cache implementation
*/
import type { CacheHandlers, Milliseconds } from "./types";
export class InMemoryCache<T> implements CacheHandlers<T> {
private cache: Map<string, { value: T; expiry: number }> = new Map();
public type = "in-memory";
async set(key: string, value: T, ttl: Milliseconds): Promise<string> {
this.cache.set(key, { value, expiry: Date.now() + ttl });
return "OK";
}
async get(key: string): Promise<T | null> {
const data = this.cache.get(key);
if (data && data.expiry >= Date.now()) {
return data.value;
}
this.cache.delete(key);
return null;
}
async has(key: string): Promise<boolean> {
const data = await this.get(key);
return data != null;
}
async remove(key: string): Promise<boolean> {
return this.cache.delete(key);
}
async removePattern(pattern: string): Promise<Array<boolean>> {
const keysToDelete = Array.from(this.cache.keys()).filter((key) =>
key.includes(pattern)
);
return keysToDelete.map((key) => this.cache.delete(key));
}
async keys(): Promise<string[]> {
return Array.from(this.cache.keys());
}
async clear(): Promise<boolean> {
this.cache.clear();
return true;
}
}