Readme

Replacement for Deno KV for Val Town on top of @std/sqlite.

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
import { sqlite } from "https://esm.town/v/std/sqlite?v=6";
import superjson from "npm:superjson";
export class DenoSyntheticKV {
name: string;
created: boolean;
constructor(name: string) {
this.name = name;
}
async open() {
if (this.created) return;
this.created = true;
await sqlite.execute(`CREATE TABLE IF NOT EXISTS ${this.name} (key TEXT PRIMARY KEY, value TEXT)`);
return;
}
async set(key: any, value: any) {
await this.open();
const encodedKey = superjson.stringify(key);
const encodedValue = superjson.stringify(value);
await sqlite.execute({
sql: `INSERT OR REPLACE INTO ${this.name} (key, value) VALUES (?, ?)`,
args: [encodedKey, encodedValue],
});
}
async get<A>(key: any): Promise<{ value: A | null }> {
await this.open();
const encodedKey = superjson.stringify(key);
const response = await sqlite.execute({
sql: `SELECT value FROM ${this.name} WHERE key = ?`,
args: [encodedKey],
});
if (response.rows.length === 0) {
return { value: null };
}
return { value: superjson.parse(response.rows[0][0]) as A };
}
async delete(key: any) {
await this.open();
const encodedKey = superjson.stringify(key);
await sqlite.execute({
sql: `DELETE FROM ${this.name} WHERE key = ?`,
args: [encodedKey],
});
}
}
👆 This is a val. Vals are TypeScript snippets of code, written in the browser and run on our servers. Create scheduled functions, email yourself, and persist small pieces of data — all from the browser.