| 44 | ]; |
| 45 | |
| 46 | export class KVStorage { |
| 47 | private readonly db: LazyDatabaseAccessor<RawDatabaseSchema>; |
| 48 | constructor(db: LazyDatabaseAccessor) { |
| 49 | this.db = db as unknown as LazyDatabaseAccessor<RawDatabaseSchema>; |
| 50 | } |
| 51 | |
| 52 | async read<T extends keyof KV>(key: T): Promise<KV[T] | undefined> { |
| 53 | const result = await this.db.then((db) => |
| 54 | db |
| 55 | .selectFrom("kv") |
| 56 | .where("key", "==", key) |
| 57 | .select("value") |
| 58 | .limit(1) |
| 59 | .executeTakeFirst() |
| 60 | ); |
| 61 | if (!result?.value) return; |
| 62 | return JSON.parse(result.value) as KV[T]; |
| 63 | } |
| 64 | |
| 65 | async write<T extends keyof KV>(key: T, value: KV[T]) { |
| 66 | await this.db.then((db) => |
| 67 | db |
| 68 | .replaceInto("kv") |
| 69 | .values({ |
| 70 | key, |
| 71 | value: JSON.stringify(value), |
| 72 | dateModified: Date.now() |
| 73 | }) |
| 74 | .execute() |
| 75 | ); |
| 76 | } |
| 77 | |
| 78 | async delete<T extends keyof KV>(key: T) { |
| 79 | await this.db.then((db) => |
| 80 | db.deleteFrom("kv").where("key", "==", key).execute() |
| 81 | ); |
| 82 | } |
| 83 | |
| 84 | async clear() { |
| 85 | await this.db.then((db) => db.deleteFrom("kv").execute()); |
| 86 | } |
| 87 | } |
nothing calls this directly
no outgoing calls
no test coverage detected