-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathkv.ts
52 lines (47 loc) · 1.18 KB
/
kv.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
export async function openKv(): Promise<Kv> {
return new Kv(
await Deno.openKv(),
await caches.open("kv-cache"),
);
}
export class Kv {
kv: Deno.Kv;
cache: Cache;
constructor(kv: Deno.Kv, cache: Cache) {
this.kv = kv;
this.cache = cache;
}
async get<T = unknown>(key: Deno.KvKey): Promise<Deno.KvEntryMaybe<T>> {
const cached = await this.cache.match(new URL(key.toString(), "http://kv"));
if (cached) {
return {
key,
value: await cached.json(),
versionstamp: null,
};
}
const result = await this.kv.get<T>(key);
if (result.value) {
await this.cache.put(
new URL(key.toString(), "http://kv"),
new Response(JSON.stringify(result.value)),
);
}
return result;
}
async set(
key: Deno.KvKey,
value: unknown,
options?: { expireIn?: number },
) {
await this.kv.set(key, value, options);
await this.cache.put(
new URL(key.toString(), "http://kv"),
new Response(JSON.stringify(value)),
);
}
async delete(key: Deno.KvKey) {
await this.kv.delete(key);
await this.cache.put(new URL(key.toString(), "http://kv"), new Response());
}
}