-
Notifications
You must be signed in to change notification settings - Fork 4
/
resources_kv.ts
52 lines (43 loc) · 1.42 KB
/
resources_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
// Rather than vendoring the path utility from Deno:
// "https://deno.land/[email protected]/path/mod.ts";
// We can use the node:path module, which is usable in Deno/Deno Deploy
import { join } from "node:path";
import defaultResources from "./default_resources.js";
// Init Deno KV database path
let kvPath;
if (!Deno.env.get("DENO_DEPLOYMENT_ID")) {
// In non-Deno Deploy environments, use a local folder in the current working
// directory for data storage
const kvDir = join(Deno.cwd(), ".kv");
try {
await Deno.mkdir(kvDir, { recursive: true, mode: 0o777 });
} catch (err) {
// Already existing is fine, throw others though
if (err.name !== "AlreadyExists") {
throw err;
}
}
kvPath = join(kvDir, "kv.db");
}
const db = await Deno.openKv(kvPath);
export interface Resource {
url: string;
title: string;
summary: string;
}
export async function addResource(resource: Resource) {
return await db.set(["resources", resource.title], resource);
}
export async function listResources(): Promise<Resource[]> {
const iter = db.list({ prefix: ["resources"] });
const resources = [];
for await (const res of iter) resources.push(res.value as Resource);
return resources;
}
export async function deleteResource(title: string) {
return await db.delete(["resources", title]);
}
// Bootstrap the database with the default resources
defaultResources.forEach((resource) => {
addResource(resource);
});