///
import { type Entry } from './item'
const DB_NAME = "append-only-list"
const STORE = "entries"
let _db: IDBDatabase | null = null
function openDB(): Promise {
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 {
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 {
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 {
await idbPut([entry])
_ws?.send(JSON.stringify(entry))
}