-
Notifications
You must be signed in to change notification settings - Fork 148
/
Copy pathcloudflare-kv-binding.ts
64 lines (55 loc) · 1.56 KB
/
cloudflare-kv-binding.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
64
/// <reference types="@cloudflare/workers-types" />
import { defineDriver } from "./utils";
export interface KVOptions {
binding?: string | KVNamespace;
}
// https://developers.cloudflare.com/workers/runtime-apis/kv
export default defineDriver((opts: KVOptions = {}) => {
const binding = getBinding(opts.binding);
async function getKeys(base?: string) {
const kvList = await binding.list(base ? { prefix: base } : undefined);
return kvList.keys.map((key) => key.name);
}
return {
name: "cloudflare-kv-binding",
options: opts,
async hasItem(key) {
return (await binding.get(key)) !== null;
},
getItem(key) {
return binding.get(key);
},
setItem(key, value) {
return binding.put(key, value);
},
removeItem(key) {
return binding.delete(key);
},
// TODO: use this.getKeys once core is fixed
getKeys,
async clear() {
const keys = await getKeys();
await Promise.all(keys.map((key) => binding.delete(key)));
},
};
});
function getBinding(binding: KVNamespace | string = "STORAGE") {
let bindingName = "[binding]";
if (typeof binding === "string") {
bindingName = binding;
binding = (globalThis as any)[bindingName] as KVNamespace;
}
if (!binding) {
throw new Error(
`Invalid Cloudflare KV binding '${bindingName}': ${binding}`
);
}
for (const key of ["get", "put", "delete"]) {
if (!(key in binding)) {
throw new Error(
`Invalid Cloudflare KV binding '${bindingName}': '${key}' key is missing`
);
}
}
return binding;
}