Files
vpinball/lib/pinball/tableLibrary.ts
T

73 lines
2.4 KiB
TypeScript
Raw Normal View History

// Persists uploaded tables (and their optional ROM zip) in the browser via
// IndexedDB, so a returning visitor can replay a table without re-uploading
// it. Blobs are stored as-is (File objects are Blobs) rather than converted
// to ArrayBuffer up front — IndexedDB clones Blobs without loading their
// bytes into JS memory, so a large library doesn't sit resident until a
// specific entry is actually played.
const DB_NAME = "vpinball-library";
const DB_VERSION = 1;
const STORE = "tables";
export interface LibraryEntry {
id: string;
name: string;
sizeBytes: number;
addedAt: number;
vpxBlob: Blob;
romFileName?: string;
romBlob?: Blob;
}
export type LibraryEntryMeta = Omit<LibraryEntry, "vpxBlob" | "romBlob">;
function openDb(): Promise<IDBDatabase> {
return new Promise((resolve, reject) => {
const request = indexedDB.open(DB_NAME, DB_VERSION);
request.onupgradeneeded = () => {
request.result.createObjectStore(STORE, { keyPath: "id" });
};
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
}
async function withStore<T>(mode: IDBTransactionMode, fn: (store: IDBObjectStore) => IDBRequest<T>): Promise<T> {
const db = await openDb();
try {
return await new Promise<T>((resolve, reject) => {
const tx = db.transaction(STORE, mode);
const request = fn(tx.objectStore(STORE));
request.onsuccess = () => resolve(request.result);
request.onerror = () => reject(request.error);
});
} finally {
db.close();
}
}
export async function saveToLibrary(entry: LibraryEntry): Promise<void> {
await withStore("readwrite", (store) => store.put(entry));
}
export async function listLibrary(): Promise<LibraryEntryMeta[]> {
const entries = await withStore<LibraryEntry[]>("readonly", (store) => store.getAll());
return entries
.map((entry): LibraryEntryMeta => ({
id: entry.id,
name: entry.name,
sizeBytes: entry.sizeBytes,
addedAt: entry.addedAt,
romFileName: entry.romFileName,
}))
.sort((a, b) => b.addedAt - a.addedAt);
}
export async function getLibraryEntry(id: string): Promise<LibraryEntry | undefined> {
return withStore<LibraryEntry | undefined>("readonly", (store) => store.get(id));
}
export async function deleteFromLibrary(id: string): Promise<void> {
await withStore("readwrite", (store) => store.delete(id));
}