wren/val Public Public: anyone can read this; nobody can change it.

forked from benjivers/val

workbenchthis machine
Files 3c63a82833bc2b178340f47c85d7acc2a4952706
1
/**
2
 * What survives a restart: finished matches. The live match lives in memory
3
 * — it is gone the moment the process is — but its result is written here,
4
 * under FORGE_APP_DATA, so the page can say what happened before you arrived.
5
 */
6
7
import { Database } from "bun:sqlite";
8
import { mkdirSync } from "node:fs";
9
import { join } from "node:path";
10
11
const dataDir = process.env.FORGE_APP_DATA ?? "./data";
12
mkdirSync(dataDir, { recursive: true });
13
14
export const db = new Database(join(dataDir, "app.db"));
15
db.exec("PRAGMA journal_mode = WAL");
16
db.exec(
17
  `CREATE TABLE IF NOT EXISTS result (
18
     id INTEGER PRIMARY KEY,
19
     summary TEXT NOT NULL,
20
     red INTEGER NOT NULL,
21
     blue INTEGER NOT NULL,
22
     rounds INTEGER NOT NULL,
23
     ended_at TEXT NOT NULL DEFAULT (datetime('now'))
24
   )`,
25
);
26
27
export type Result = { summary: string; red: number; blue: number; rounds: number; ended_at: string };
28
29
export const recordResult = (summary: string, red: number, blue: number, rounds: number): void => {
30
  db.query("INSERT INTO result (summary, red, blue, rounds) VALUES (?1, ?2, ?3, ?4)").run(
31
    summary.slice(0, 120),
32
    red,
33
    blue,
34
    rounds,
35
  );
36
};
37
38
export const recentResults = (limit = 5): Result[] =>
39
  db
40
    .query<Result, [number]>(
41
      "SELECT summary, red, blue, rounds, ended_at FROM result ORDER BY id DESC LIMIT ?1",
42
    )
43
    .all(Math.max(1, Math.min(50, limit)));
↑↓ navigate ↵ open esc close
↑↓ navigate ↵ open esc close

Keyboard shortcuts