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

capacitor-persistence.test.ts

222 lines5.5 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 createCapacitorSQLitePersistence,
8 persistedCollectionOptions,
9} from '../src'
10import { createCapacitorSQLiteTestDatabase } from './helpers/capacitor-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(
29 join(tmpdir(), `db-capacitor-persistence-test-`),
30 )
31 const dbPath = join(tempDirectory, `state.sqlite`)
32 activeCleanupFns.push(() => {
33 rmSync(tempDirectory, { recursive: true, force: true })
34 })
35 return dbPath
37​
38it(`persists data across app restart (close and reopen)`, async () => {
39 const dbPath = createTempSqlitePath()
40 const collectionId = `todos-restart`
41​
42 const firstDatabase = createCapacitorSQLiteTestDatabase({ filename: dbPath })
43 const firstPersistence = createCapacitorSQLitePersistence({
44 database: firstDatabase,
45 })
46 const firstAdapter = firstPersistence.adapter
47​
48 await firstAdapter.applyCommittedTx(collectionId, {
49 txId: `tx-restart-1`,
50 term: 1,
51 seq: 1,
52 rowVersion: 1,
53 mutations: [
54 {
55 type: `insert`,
56 key: `1`,
57 value: {
58 id: `1`,
59 title: `Survives restart`,
60 score: 10,
61 },
62 },
63 ],
64 })
65 await firstDatabase.close()
66​
67 const secondDatabase = createCapacitorSQLiteTestDatabase({ filename: dbPath })
68 activeCleanupFns.push(() => secondDatabase.close())
69 const secondPersistence = createCapacitorSQLitePersistence({
70 database: secondDatabase,
71 })
72 const secondAdapter = secondPersistence.adapter
73​
74 const rows = await secondAdapter.loadSubset(collectionId, {})
75 expect(rows).toEqual([
76 {
77 key: `1`,
78 value: {
79 id: `1`,
80 title: `Survives restart`,
81 score: 10,
82 },
83 },
84 ])
85})
86​
87it(`keeps all committed rows under rapid mutation bursts`, async () => {
88 const dbPath = createTempSqlitePath()
89 const collectionId = `todos-burst`
90 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
91 activeCleanupFns.push(() => database.close())
92​
93 const persistence = createCapacitorSQLitePersistence({
94 database,
95 })
96 const adapter = persistence.adapter
97​
98 const burstSize = 50
99 for (let index = 0; index < burstSize; index++) {
100 const rowId = String(index + 1)
101 await adapter.applyCommittedTx(collectionId, {
102 txId: `tx-burst-${rowId}`,
103 term: 1,
104 seq: index + 1,
105 rowVersion: index + 1,
106 mutations: [
107 {
108 type: `insert`,
109 key: rowId,
110 value: {
111 id: rowId,
112 title: `Todo ${rowId}`,
113 score: index,
114 },
115 },
116 ],
117 })
118 }
119​
120 const rows = await adapter.loadSubset(collectionId, {})
121 expect(rows).toHaveLength(burstSize)
122})
123​
124it(`shares persistence across multiple collections on one database`, async () => {
125 const dbPath = createTempSqlitePath()
126 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
127 activeCleanupFns.push(() => database.close())
128​
129 const persistence = createCapacitorSQLitePersistence({
130 database,
131 })
132​
133 await persistence.adapter.applyCommittedTx(`todos-a`, {
134 txId: `tx-a-1`,
135 term: 1,
136 seq: 1,
137 rowVersion: 1,
138 mutations: [
139 {
140 type: `insert`,
141 key: `a1`,
142 value: {
143 id: `a1`,
144 title: `A`,
145 score: 1,
146 },
147 },
148 ],
149 })
150​
151 await persistence.adapter.applyCommittedTx(`todos-b`, {
152 txId: `tx-b-1`,
153 term: 1,
154 seq: 1,
155 rowVersion: 1,
156 mutations: [
157 {
158 type: `insert`,
159 key: `b1`,
160 value: {
161 id: `b1`,
162 title: `B`,
163 score: 2,
164 },
165 },
166 ],
167 })
168​
169 const rowsA = await persistence.adapter.loadSubset(`todos-a`, {})
170 const rowsB = await persistence.adapter.loadSubset(`todos-b`, {})
171​
172 expect(rowsA.map((row) => row.key)).toEqual([`a1`])
173 expect(rowsB.map((row) => row.key)).toEqual([`b1`])
174})
175​
176it(`resumes persisted sync after simulated app lifecycle transitions`, async () => {
177 const dbPath = createTempSqlitePath()
178 const collectionId = `todos-lifecycle`
179 const database = createCapacitorSQLiteTestDatabase({ filename: dbPath })
180 activeCleanupFns.push(() => database.close())
181​
182 const persistence = createCapacitorSQLitePersistence({
183 database,
184 })
185 const collection = createCollection(
186 persistedCollectionOptions<Todo, string>({
187 id: collectionId,
188 getKey: (todo) => todo.id,
189 persistence,
190 syncMode: `eager`,
191 }),
192 )
193 activeCleanupFns.push(() => collection.cleanup())
194​
195 await collection.stateWhenReady()
196​
197 const initialInsert = collection.insert({
198 id: `1`,
199 title: `Before background`,
200 score: 1,
201 })
202 await initialInsert.isPersisted.promise
203​
204 await collection.cleanup()
205 collection.startSyncImmediate()
206 await collection.stateWhenReady()
207​
208 const postResumeInsert = collection.insert({
209 id: `2`,
210 title: `Post resume write`,
211 score: 2,
212 })
213 await postResumeInsert.isPersisted.promise
214​
215 const persistedRows = await persistence.adapter.loadSubset(collectionId, {})
216 expect(persistedRows).toEqual(
217 expect.arrayContaining([
218 expect.objectContaining({ key: `1` }),
219 expect.objectContaining({ key: `2` }),
220 ]),
221 )
222})