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],
});
}
}