Something went wrong. Try again.
an append only list
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117import { test, expect, beforeAll, afterAll } from "bun:test"import { Database } from "bun:sqlite"import { initDb, getEntriesData, saveEntry } from "./api"
let server: ReturnType<typeof Bun.serve>let db: Databaselet wsUrl: string
beforeAll(() => { db = new Database(":memory:") initDb(db)
const clients = new Set<Bun.ServerWebSocket<undefined>>()
server = Bun.serve<undefined>({ port: 0, fetch(req, server) { const { pathname } = new URL(req.url) if (pathname === "/ws") { if (server.upgrade(req)) return return new Response("WebSocket upgrade failed", { status: 400 }) } return new Response("<html><body>app</body></html>", { headers: { "Content-Type": "text/html; charset=utf-8" }, }) }, websocket: { open(ws) { clients.add(ws) ws.send(JSON.stringify({ type: "init", entries: getEntriesData(db) })) }, message(ws, msg) { const entry = JSON.parse(msg as string) saveEntry(db, entry) const payload = JSON.stringify({ type: "entry", entry }) for (const client of clients) client.send(payload) }, close(ws) { clients.delete(ws) }, }, })
wsUrl = `ws://localhost:${server.port}/ws`})
afterAll(() => { server.stop() db.close()})
const mockEntry = { id: "deadbeef", created: 1_000_000, item: { key: "k1", text: "hello", checked: null, created: 1_000_000 },}
function connectWS(): Promise<{ ws: WebSocket; messages: unknown[] }> { return new Promise((resolve, reject) => { const messages: unknown[] = [] const ws = new WebSocket(wsUrl) ws.onmessage = (e) => messages.push(JSON.parse(e.data as string)) ws.onopen = () => resolve({ ws, messages }) ws.onerror = reject })}
function waitFor(condition: () => boolean, timeout = 500): Promise<void> { return new Promise((resolve, reject) => { const iv = setInterval(() => { if (condition()) { clearInterval(iv); resolve() } }, 10) setTimeout(() => { clearInterval(iv); reject(new Error("waitFor timeout")) }, timeout) })}
test("WS open sends init with empty entries", async () => { const { ws, messages } = await connectWS() await waitFor(() => messages.length >= 1) ws.close() expect(messages[0]).toEqual({ type: "init", entries: [] })})
test("WS message saves entry and broadcasts to all subscribers", async () => { const { ws: ws1, messages: m1 } = await connectWS() const { ws: ws2, messages: m2 } = await connectWS() await waitFor(() => m1.length >= 1 && m2.length >= 1)
ws1.send(JSON.stringify(mockEntry)) await waitFor(() => m1.length >= 2 && m2.length >= 2)
ws1.close() ws2.close()
const isBroadcast = (m: unknown) => (m as { type: string; entry: { id: string } }).type === "entry" && (m as { type: string; entry: { id: string } }).entry.id === "deadbeef"
expect(m1.some(isBroadcast)).toBe(true) expect(m2.some(isBroadcast)).toBe(true)})
test("WS init includes previously saved entries", async () => { const { ws, messages } = await connectWS() await waitFor(() => messages.length >= 1) ws.close()
const init = messages[0] as { type: string; entries: { id: string }[] } | undefined expect(init?.type).toBe("init") expect(init?.entries).toHaveLength(1) expect(init?.entries[0]?.id).toBe("deadbeef")})
test("GET / returns HTML fallback", async () => { const res = await fetch(`http://localhost:${server.port}/`) expect(res.status).toBe(200) expect(res.headers.get("content-type")).toContain("text/html")})