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

expo-persistence.test.ts

186 lines4.8 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterEach, expect, it } from 'vitest'
5import { createCollection } from '@tanstack/db'
6import { createExpoSQLitePersistence, persistedCollectionOptions } from '../src'
7import { createExpoSQLiteTestDatabase } from './helpers/expo-sqlite-test-db'
8​
9type Todo = {
10 id: string
11 title: string
12 score: number
14​
15const activeCleanupFns: Array<() => void | Promise<void>> = []
16​
17afterEach(async () => {
18 while (activeCleanupFns.length > 0) {
19 const cleanupFn = activeCleanupFns.pop()
20 await Promise.resolve(cleanupFn?.())
21 }
22})
23​
24function createTempSqlitePath(): string {
25 const tempDirectory = mkdtempSync(join(tmpdir(), `db-expo-persistence-test-`))
26 const dbPath = join(tempDirectory, `state.sqlite`)
27 activeCleanupFns.push(() => {
28 rmSync(tempDirectory, { recursive: true, force: true })
29 })
30 return dbPath
32​
33it(`persists data across app restart (close and reopen)`, async () => {
34 const dbPath = createTempSqlitePath()
35 const collectionId = `todos-restart`
36​
37 const firstDatabase = createExpoSQLiteTestDatabase({ filename: dbPath })
38 const firstPersistence = createExpoSQLitePersistence({
39 database: firstDatabase,
40 })
41 const firstAdapter = firstPersistence.adapter
42​
43 await firstAdapter.applyCommittedTx(
44 { kind: `eager`, collectionId: collectionId },
45 {
46 txId: `tx-restart-1`,
47 term: 1,
48 seq: 1,
49 rowVersion: 1,
50 mutations: [
51 {
52 type: `insert`,
53 key: `1`,
54 value: {
55 id: `1`,
56 title: `Survives restart`,
57 score: 10,
58 },
59 },
60 ],
61 },
62 )
63 await firstDatabase.closeAsync()
64​
65 const secondDatabase = createExpoSQLiteTestDatabase({ filename: dbPath })
66 activeCleanupFns.push(() => secondDatabase.closeAsync())
67 const secondPersistence = createExpoSQLitePersistence({
68 database: secondDatabase,
69 })
70 const secondAdapter = secondPersistence.adapter
71​
72 const rows = await secondAdapter.loadSubset(
73 { kind: `eager`, collectionId: collectionId },
74 {},
75 )
76 expect(rows).toEqual([
77 {
78 key: `1`,
79 value: {
80 id: `1`,
81 title: `Survives restart`,
82 score: 10,
83 },
84 },
85 ])
86})
87​
88it(`keeps all committed rows under rapid mutation bursts`, async () => {
89 const dbPath = createTempSqlitePath()
90 const collectionId = `todos-burst`
91 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
92 activeCleanupFns.push(() => database.closeAsync())
93​
94 const persistence = createExpoSQLitePersistence({
95 database,
96 })
97 const adapter = persistence.adapter
98​
99 const burstSize = 50
100 for (let index = 0; index < burstSize; index++) {
101 const rowId = String(index + 1)
102 await adapter.applyCommittedTx(
103 { kind: `eager`, collectionId: collectionId },
104 {
105 txId: `tx-burst-${rowId}`,
106 term: 1,
107 seq: index + 1,
108 rowVersion: index + 1,
109 mutations: [
110 {
111 type: `insert`,
112 key: rowId,
113 value: {
114 id: rowId,
115 title: `Todo ${rowId}`,
116 score: index,
117 },
118 },
119 ],
120 },
121 )
122 }
123​
124 const rows = await adapter.loadSubset(
125 { kind: `eager`, collectionId: collectionId },
126 {},
127 )
128 expect(rows).toHaveLength(burstSize)
129})
130​
131it(`resumes persisted sync after simulated background/foreground transitions`, async () => {
132 const dbPath = createTempSqlitePath()
133 const collectionId = `todos-lifecycle`
134 const database = createExpoSQLiteTestDatabase({ filename: dbPath })
135 activeCleanupFns.push(() => database.closeAsync())
136​
137 const persistence = createExpoSQLitePersistence({
138 database,
139 })
140 const collection = createCollection(
141 persistedCollectionOptions<Todo, string>({
142 id: collectionId,
143 getKey: (todo) => todo.id,
144 persistence,
145 syncMode: `eager`,
146 }),
147 )
148 activeCleanupFns.push(() => collection.cleanup())
149​
150 await collection.stateWhenReady()
151​
152 const initialInsert = collection.insert({
153 id: `1`,
154 title: `Before background`,
155 score: 1,
156 })
157 await initialInsert.when(`settled`)
158 expect(collection.get(`1`)?.title).toBe(`Before background`)
159​
160 await collection.cleanup()
161 collection.startSyncImmediate()
162 await collection.stateWhenReady()
163​
164 const postResumeInsert = collection.insert({
165 id: `2`,
166 title: `Post resume write`,
167 score: 2,
168 })
169 await postResumeInsert.when(`settled`)
170 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
171​
172 const persistedRows = await persistence.adapter.loadSubset(
173 { kind: `eager`, collectionId: collectionId },
174 {},
175 )
176 expect(persistedRows).toEqual(
177 expect.arrayContaining([
178 expect.objectContaining({
179 key: `1`,
180 }),
181 expect.objectContaining({
182 key: `2`,
183 }),
184 ]),
185 )
186})