Something went wrong. Try again.
an append only list
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374/// <reference lib="dom" />import { type Entry } from './item'
const DB_NAME = "append-only-list"const STORE = "entries"
let _db: IDBDatabase | null = null
function openDB(): Promise<IDBDatabase> { if (_db) return Promise.resolve(_db) return new Promise((resolve, reject) => { const req = indexedDB.open(DB_NAME, 1) req.onupgradeneeded = () => { if (!req.result.objectStoreNames.contains(STORE)) { req.result.createObjectStore(STORE, { keyPath: "id" }) } } req.onsuccess = () => { _db = req.result; resolve(req.result) } req.onerror = () => reject(req.error) })}
async function idbGetAll(): Promise<Entry[]> { const db = await openDB() return new Promise((resolve, reject) => { const req = db.transaction(STORE).objectStore(STORE).getAll() req.onsuccess = () => resolve(req.result as Entry[]) req.onerror = () => reject(req.error) })}
async function idbPut(entries: Entry[]): Promise<void> { const db = await openDB() return new Promise((resolve, reject) => { const tx = db.transaction(STORE, "readwrite") for (const e of entries) tx.objectStore(STORE).put(e) tx.oncomplete = () => resolve() tx.onerror = () => reject(tx.error) })}
let _ws: WebSocket | null = null
export function connectWS(handlers: { onInit: (entries: Entry[]) => void onEntry: (entry: Entry) => void}): void { const ws = new WebSocket(`ws://${location.host}/ws`) _ws = ws
ws.onmessage = async (e) => { const msg = JSON.parse(e.data as string) as | { type: "init"; entries: Entry[] } | { type: "entry"; entry: Entry }
if (msg.type === "init") { await idbPut(msg.entries) handlers.onInit(msg.entries) } else if (msg.type === "entry") { await idbPut([msg.entry]) handlers.onEntry(msg.entry) } }
ws.onerror = ws.onclose = async () => { handlers.onInit(await idbGetAll()) }}
export async function saveEntry(entry: Entry): Promise<void> { await idbPut([entry]) _ws?.send(JSON.stringify(entry))}