Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

host-driver.ts

117 lines3.6 KB

1/** Shared production driver for real pages and dedicated workers. Expected
2 * rows stay in host-oracle.spec.ts. Native events and storage supply all premises.
3 */
4import { createCollection } from '@tanstack/db'
5import { createIndexedDB, indexedDBCollectionOptions } from '../src'
6​
7export type HostRow = { id: string | number; name: string }
8export type HostCommand =
9 | { type: 'insert'; store: string; rows: Array<HostRow> }
10 | { type: 'import'; store: string; rows: Array<HostRow> }
11 | { type: 'update'; store: string; key: string | number; name: string }
12 | { type: 'clear'; store: string }
13 | { type: 'observe' }
14 | { type: 'status' }
15 | { type: 'close' }
16 | { type: 'cleanup' }
17export type HostSetup = { database: string; stores: Array<string> }
18function rows(values: Iterable<HostRow>) {
19 return [...values]
20 .map(({ id, name }) => ({ id, name }))
21 .sort((a, b) => JSON.stringify(a.id).localeCompare(JSON.stringify(b.id)))
23export async function createHost({ database, stores }: HostSetup) {
24 const descriptor = await createIndexedDB({
25 name: database,
26 stores,
27 version: 1,
28 })
29 let nativeClose = 0
30 descriptor.db.addEventListener('close', () => {
31 nativeClose++
32 })
33 const collections = new Map(
34 stores.map((name) => [
35 name,
36 createCollection(
37 indexedDBCollectionOptions<HostRow>({
38 db: descriptor,
39 name,
40 getKey: (row) => row.id,
41 }),
42 ),
43 ]),
44 )
45 async function dispose() {
46 const results = await Promise.allSettled(
47 [...collections.values()].map((c) => c.cleanup()),
48 )
49 descriptor.close()
50 const failures = results.flatMap((result) =>
51 result.status === 'rejected' ? [result.reason as unknown] : [],
52 )
53 if (failures.length)
54 throw new AggregateError(failures, 'host cleanup failed')
55 }
56 try {
57 await Promise.all([...collections.values()].map((c) => c.preload()))
58 } catch (error) {
59 try {
60 await dispose()
61 } catch (cleanup) {
62 throw new AggregateError(
63 [error, cleanup],
64 'host setup and cleanup failed',
65 { cause: error },
66 )
67 }
68 throw error
69 }
70 async function raw(store: string) {
71 const tx = descriptor.db.transaction(store)
72 const request = tx.objectStore(store).getAll()
73 return new Promise<Array<HostRow>>((resolve, reject) => {
74 tx.oncomplete = () => resolve(request.result)
75 tx.onabort = () => reject(tx.error)
76 })
77 }
78 return async (command: HostCommand) => {
79 if (command.type === 'cleanup') {
80 await dispose()
81 return
82 }
83 if (command.type === 'close') {
84 descriptor.close()
85 return
86 }
87 if (command.type === 'status')
88 return {
89 nativeClose,
90 collections: [...collections].map(([store, c]) => ({
91 store,
92 status: c.status,
93 rows: rows(c.values()),
94 })),
95 }
96 if (command.type === 'observe')
97 return Promise.all(
98 [...collections].map(async ([store, c]) => ({
99 store,
100 status: c.status,
101 rows: rows(c.values()),
102 durable: rows(await raw(store)),
103 exported: rows(await c.utils.exportData()),
104 })),
105 )
106 const c = collections.get(command.store)!
107 if (command.type === 'insert')
108 await c.insert(command.rows).isPersisted.promise
109 else if (command.type === 'import') await c.utils.importData(command.rows)
110 else if (command.type === 'clear') await c.utils.clearObjectStore()
111 else
112 await c.update(command.key, (draft) => {
113 draft.name = command.name
114 }).isPersisted.promise
115 return undefined
116 }