/** * What survives a restart: finished matches. The live match lives in memory * — it is gone the moment the process is — but its result is written here, * under FORGE_APP_DATA, so the page can say what happened before you arrived. */ import { Database } from "bun:sqlite"; import { mkdirSync } from "node:fs"; import { join } from "node:path"; const dataDir = process.env.FORGE_APP_DATA ?? "./data"; mkdirSync(dataDir, { recursive: true }); export const db = new Database(join(dataDir, "app.db")); db.exec("PRAGMA journal_mode = WAL"); db.exec( `CREATE TABLE IF NOT EXISTS result ( id INTEGER PRIMARY KEY, summary TEXT NOT NULL, red INTEGER NOT NULL, blue INTEGER NOT NULL, rounds INTEGER NOT NULL, ended_at TEXT NOT NULL DEFAULT (datetime('now')) )`, ); export type Result = { summary: string; red: number; blue: number; rounds: number; ended_at: string }; export const recordResult = (summary: string, red: number, blue: number, rounds: number): void => { db.query("INSERT INTO result (summary, red, blue, rounds) VALUES (?1, ?2, ?3, ?4)").run( summary.slice(0, 120), red, blue, rounds, ); }; export const recentResults = (limit = 5): Result[] => db .query( "SELECT summary, red, blue, rounds, ended_at FROM result ORDER BY id DESC LIMIT ?1", ) .all(Math.max(1, Math.min(50, limit)));