-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathmemory.ts
58 lines (48 loc) · 1.25 KB
/
memory.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
import { Adapter } from "./adapter.ts";
export class MemoryAdapter implements Adapter {
namespaces: Map<
string,
Map<string, { value: string; ttl: number }>
> = new Map();
checkNamespace(ns: string) {
if (this.namespaces.has(ns)) return;
else this.namespaces.set(ns, new Map());
}
ns(ns: string) {
this.checkNamespace(ns);
return this.namespaces.get(ns);
}
// deno-lint-ignore no-explicit-any
set(k: string, v: any, ns = "", ttl = 0) {
const n = this.ns(ns);
n?.set(k, { value: v, ttl });
return this;
}
get(k: string, ns = "") {
const n = this.ns(ns);
const v = n?.get(k);
return !v ? undefined : { key: k, ns, value: v.value, ttl: v.ttl };
}
has(k: string, ns = "") {
return this.ns(ns)?.has(k) ?? false;
}
delete(k: string, ns = "") {
const n = this.ns(ns);
return n?.delete(k) ?? false;
}
keys(ns = "") {
return [...(this.ns(ns)?.keys() ?? [])];
}
clear(ns = "") {
this.namespaces.set(ns, new Map());
return this;
}
deleteExpired(ns = "") {
const n = this.ns(ns)!;
for (const e of n.entries()) {
if (e[1].ttl !== 0 && Date.now() > e[1].ttl) {
n.delete(e[0]);
}
}
}
}