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

react-native-persistence.test.ts

312 lines8.2 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 {
7 createReactNativeSQLitePersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createOpSQLiteTestDatabase } from './helpers/op-sqlite-test-db'
11​
12type Todo = {
13 id: string
14 title: string
15 score: number
17​
18const activeCleanupFns: Array<() => void | Promise<void>> = []
19​
20afterEach(async () => {
21 while (activeCleanupFns.length > 0) {
22 const cleanupFn = activeCleanupFns.pop()
23 await Promise.resolve(cleanupFn?.())
24 }
25})
26​
27function createTempSqlitePath(): string {
28 const tempDirectory = mkdtempSync(join(tmpdir(), `db-rn-persistence-test-`))
29 const dbPath = join(tempDirectory, `state.sqlite`)
30 activeCleanupFns.push(() => {
31 rmSync(tempDirectory, { recursive: true, force: true })
32 })
33 return dbPath
35​
36it(`persists data across app restart (close and reopen)`, async () => {
37 const dbPath = createTempSqlitePath()
38 const collectionId = `todos-restart`
39​
40 const firstDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
41 const firstPersistence = createReactNativeSQLitePersistence({
42 database: firstDatabase,
43 })
44 const firstAdapter = firstPersistence.adapter
45​
46 await firstAdapter.applyCommittedTx(collectionId, {
47 txId: `tx-restart-1`,
48 term: 1,
49 seq: 1,
50 rowVersion: 1,
51 mutations: [
52 {
53 type: `insert`,
54 key: `1`,
55 value: {
56 id: `1`,
57 title: `Survives restart`,
58 score: 10,
59 },
60 },
61 ],
62 })
63 await Promise.resolve(firstDatabase.close())
64​
65 const secondDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
66 activeCleanupFns.push(() => Promise.resolve(secondDatabase.close()))
67 const secondPersistence = createReactNativeSQLitePersistence({
68 database: secondDatabase,
69 })
70 const secondAdapter = secondPersistence.adapter
71​
72 const rows = await secondAdapter.loadSubset(collectionId, {})
73 expect(rows).toEqual([
74 {
75 key: `1`,
76 value: {
77 id: `1`,
78 title: `Survives restart`,
79 score: 10,
80 },
81 },
82 ])
83})
84​
85it(`shared react-native api persists across expo-style restart`, async () => {
86 const dbPath = createTempSqlitePath()
87 const collectionId = `todos-restart-expo`
88​
89 const firstDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
90 const firstPersistence = createReactNativeSQLitePersistence({
91 database: firstDatabase,
92 })
93 const firstAdapter = firstPersistence.adapter
94​
95 await firstAdapter.applyCommittedTx(collectionId, {
96 txId: `tx-restart-expo-1`,
97 term: 1,
98 seq: 1,
99 rowVersion: 1,
100 mutations: [
101 {
102 type: `insert`,
103 key: `1`,
104 value: {
105 id: `1`,
106 title: `Expo survives restart`,
107 score: 10,
108 },
109 },
110 ],
111 })
112 await Promise.resolve(firstDatabase.close())
113​
114 const secondDatabase = createOpSQLiteTestDatabase({ filename: dbPath })
115 activeCleanupFns.push(() => Promise.resolve(secondDatabase.close()))
116 const secondPersistence = createReactNativeSQLitePersistence({
117 database: secondDatabase,
118 })
119 const secondAdapter = secondPersistence.adapter
120​
121 const rows = await secondAdapter.loadSubset(collectionId, {})
122 expect(rows).toEqual([
123 {
124 key: `1`,
125 value: {
126 id: `1`,
127 title: `Expo survives restart`,
128 score: 10,
129 },
130 },
131 ])
132})
133​
134it(`keeps all committed rows under rapid mutation bursts`, async () => {
135 const dbPath = createTempSqlitePath()
136 const collectionId = `todos-burst`
137 const database = createOpSQLiteTestDatabase({ filename: dbPath })
138 activeCleanupFns.push(() => Promise.resolve(database.close()))
139​
140 const persistence = createReactNativeSQLitePersistence({
141 database,
142 })
143 const adapter = persistence.adapter
144​
145 const burstSize = 50
146 for (let index = 0; index < burstSize; index++) {
147 const rowId = String(index + 1)
148 await adapter.applyCommittedTx(collectionId, {
149 txId: `tx-burst-${rowId}`,
150 term: 1,
151 seq: index + 1,
152 rowVersion: index + 1,
153 mutations: [
154 {
155 type: `insert`,
156 key: rowId,
157 value: {
158 id: rowId,
159 title: `Todo ${rowId}`,
160 score: index,
161 },
162 },
163 ],
164 })
165 }
166​
167 const rows = await adapter.loadSubset(collectionId, {})
168 expect(rows).toHaveLength(burstSize)
169})
170​
171it(`uses a single react-native api across runtime aliases`, async () => {
172 const dbPath = createTempSqlitePath()
173 const collectionId = `todos-entrypoints`
174 const database = createOpSQLiteTestDatabase({ filename: dbPath })
175 activeCleanupFns.push(() => Promise.resolve(database.close()))
176​
177 const reactNativePersistence = createReactNativeSQLitePersistence({
178 database,
179 })
180 const sharedApiPersistence = createReactNativeSQLitePersistence({
181 database,
182 })
183​
184 await reactNativePersistence.adapter.applyCommittedTx(collectionId, {
185 txId: `tx-entrypoint-1`,
186 term: 1,
187 seq: 1,
188 rowVersion: 1,
189 mutations: [
190 {
191 type: `insert`,
192 key: `1`,
193 value: {
194 id: `1`,
195 title: `Entry point parity`,
196 score: 1,
197 },
198 },
199 ],
200 })
201​
202 const rows = await sharedApiPersistence.adapter.loadSubset(collectionId, {})
203 expect(rows[0]?.value.title).toBe(`Entry point parity`)
204})
205​
206it(`resumes persisted sync after simulated background/foreground transitions`, async () => {
207 const dbPath = createTempSqlitePath()
208 const collectionId = `todos-lifecycle`
209 const database = createOpSQLiteTestDatabase({ filename: dbPath })
210 activeCleanupFns.push(() => Promise.resolve(database.close()))
211​
212 const persistence = createReactNativeSQLitePersistence({
213 database,
214 })
215 const collection = createCollection(
216 persistedCollectionOptions<Todo, string>({
217 id: collectionId,
218 getKey: (todo) => todo.id,
219 persistence,
220 syncMode: `eager`,
221 }),
222 )
223 activeCleanupFns.push(() => collection.cleanup())
224​
225 await collection.stateWhenReady()
226​
227 const initialInsert = collection.insert({
228 id: `1`,
229 title: `Before background`,
230 score: 1,
231 })
232 await initialInsert.isPersisted.promise
233 expect(collection.get(`1`)?.title).toBe(`Before background`)
234​
235 await collection.cleanup()
236 collection.startSyncImmediate()
237 await collection.stateWhenReady()
238​
239 const postResumeInsert = collection.insert({
240 id: `2`,
241 title: `Post resume write`,
242 score: 2,
243 })
244 await postResumeInsert.isPersisted.promise
245 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
246​
247 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
248 expect(persistedRows).toEqual(
249 expect.arrayContaining([
250 expect.objectContaining({
251 key: `1`,
252 }),
253 expect.objectContaining({
254 key: `2`,
255 }),
256 ]),
257 )
258})
259​
260it(`shared api resumes persisted sync in expo-style lifecycle`, async () => {
261 const dbPath = createTempSqlitePath()
262 const collectionId = `todos-lifecycle-expo`
263 const database = createOpSQLiteTestDatabase({ filename: dbPath })
264 activeCleanupFns.push(() => Promise.resolve(database.close()))
265​
266 const persistence = createReactNativeSQLitePersistence({
267 database,
268 })
269 const collection = createCollection(
270 persistedCollectionOptions<Todo, string>({
271 id: collectionId,
272 getKey: (todo) => todo.id,
273 persistence,
274 syncMode: `eager`,
275 }),
276 )
277 activeCleanupFns.push(() => collection.cleanup())
278​
279 await collection.stateWhenReady()
280​
281 const initialInsert = collection.insert({
282 id: `1`,
283 title: `Before background`,
284 score: 1,
285 })
286 await initialInsert.isPersisted.promise
287 expect(collection.get(`1`)?.title).toBe(`Before background`)
288​
289 await collection.cleanup()
290 collection.startSyncImmediate()
291 await collection.stateWhenReady()
292​
293 const postResumeInsert = collection.insert({
294 id: `2`,
295 title: `Post resume write`,
296 score: 2,
297 })
298 await postResumeInsert.isPersisted.promise
299 expect(collection.get(`2`)?.title).toBe(`Post resume write`)
300​
301 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
302 expect(persistedRows).toEqual(
303 expect.arrayContaining([
304 expect.objectContaining({
305 key: `1`,
306 }),
307 expect.objectContaining({
308 key: `2`,
309 }),
310 ]),
311 )
312})