Something went wrong. Try again.
twinkl.social forked from kandake.africa/twinkl
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768import type { Db } from './db';
/** * Pluggable cache contract. The SQLite implementation below is the default for * the adapter-node deployment; a Redis-backed implementation can be swapped in * later without touching callers. Async by design so that swap stays invisible. */export interface Cache { get<T>(key: string): Promise<T | undefined>; set<T>(key: string, value: T, ttlMs?: number): Promise<void>; delete(key: string): Promise<void>; /** Fetch from cache, or run `load`, store the result, and return it. */ getOrLoad<T>(key: string, ttlMs: number, load: () => Promise<T>): Promise<T>;}
/** SQLite-backed cache. Replaces Blento's Cloudflare KV `CacheService`. */export class SqliteCache implements Cache { #db: Db;
constructor(db: Db) { this.#db = db; }
async get<T>(key: string): Promise<T | undefined> { const row = this.#db.prepare('SELECT value, expires_at FROM cache WHERE key = ?').get(key) as | { value: string; expires_at: number | null } | undefined;
if (!row) return undefined;
if (row.expires_at !== null && row.expires_at <= Date.now()) { this.#db.prepare('DELETE FROM cache WHERE key = ?').run(key); return undefined; }
return JSON.parse(row.value) as T; }
async set<T>(key: string, value: T, ttlMs?: number): Promise<void> { const expiresAt = ttlMs === undefined ? null : Date.now() + ttlMs; this.#db .prepare( 'INSERT INTO cache (key, value, expires_at) VALUES (?, ?, ?) ' + 'ON CONFLICT(key) DO UPDATE SET value = excluded.value, expires_at = excluded.expires_at' ) .run(key, JSON.stringify(value), expiresAt); }
async delete(key: string): Promise<void> { this.#db.prepare('DELETE FROM cache WHERE key = ?').run(key); }
async getOrLoad<T>(key: string, ttlMs: number, load: () => Promise<T>): Promise<T> { const cached = await this.get<T>(key); if (cached !== undefined) return cached; const fresh = await load(); await this.set(key, fresh, ttlMs); return fresh; }
/** Remove expired rows. Safe to call periodically; not required for correctness. */ prune(): void { this.#db .prepare('DELETE FROM cache WHERE expires_at IS NOT NULL AND expires_at <= ?') .run(Date.now()); }}