Open History to see the last commit
1import { describe, expect, it } from "vitest"
2import { createCollection } from "@tanstack/db"
3import {
4 addRxPlugin,
5 createRxDatabase,
6 getFromMapOrCreate,
7} from "rxdb/plugins/core"
8import { RxDBDevModePlugin } from "rxdb/plugins/dev-mode"
9import { getRxStorageMemory } from "rxdb/plugins/storage-memory"
10import { wrappedValidateAjvStorage } from "rxdb/plugins/validate-ajv"
11import { OPEN_RXDB_SUBSCRIPTIONS, rxdbCollectionOptions } from "../src/rxdb"
12import type { RxCollection } from "rxdb/plugins/core"
13import type { RxDBCollectionConfig } from "../src/rxdb"
14
15type TestDocType = {
16 id: string
17 name: string
18}
19type RxCollections = { test: RxCollection<TestDocType> }
20
21// Helper to advance timers and allow microtasks to flush
22const flushPromises = () => new Promise((resolve) => setTimeout(resolve, 0))
23
24describe(`RxDB Integration`, () => {
25 addRxPlugin(RxDBDevModePlugin)
26
27 let dbNameId = 0
28 function getTestData(amount: number): Array<TestDocType> {
29 return new Array(amount).fill(0).map((_v, i) => {
30 return {
31 id: i + 1 + ``,
32 name: `Item ` + (i + 1),
33 }
34 })
35 }
36
37 async function getDatababase(
38 initialDocs: Array<TestDocType> = [],
39 dbId = dbNameId++
40 ) {
41 const db = await createRxDatabase<RxCollections, unknown, unknown, unknown>(
42 {
43 name: `my-rxdb-` + dbId,
44 ignoreDuplicate: true,
45 storage: wrappedValidateAjvStorage({
46 storage: getRxStorageMemory(),
47 }),
48 }
49 )
50 const collections = await db.addCollections<RxCollections>({
51 test: {
52 schema: {
53 version: 0,
54 type: `object`,
55 primaryKey: `id`,
56 properties: {
57 id: {
58 type: `string`,
59 maxLength: 100,
60 },
61 name: {
62 type: `string`,
63 maxLength: 9,
64 },
65 },
66 },
67 },
68 })
69 const rxCollection: RxCollection<TestDocType> = collections.test
70 if (initialDocs.length > 0) {
71 const insertResult = await rxCollection.bulkInsert(initialDocs)
72 expect(insertResult.error.length).toBe(0)
73 }
74 return db
75 }
76
77 async function createTestState(
78 initialDocs: Array<TestDocType> = [],
79 config: Partial<RxDBCollectionConfig<TestDocType, any>> = {}
80 ) {
81 const db = await getDatababase(initialDocs, dbNameId++)
82 const rxCollection: RxCollection<TestDocType> = db.test
83 const options = rxdbCollectionOptions({
84 rxCollection: rxCollection,
85 startSync: true,
86 /**
87 * In tests we use a small batch size
88 * to ensure iteration works.
89 */
90 syncBatchSize: 10,
91 ...config,
92 })
93
94 const collection = createCollection(options)
95 await collection.stateWhenReady()
96
97 return {
98 collection,
99 rxCollection,
100 db,
101 }
102 }
103
104 describe(`sync`, () => {
105 it(`should initialize and fetch initial data`, async () => {
106 const initialItems = getTestData(2)
107
108 const { collection, db } = await createTestState(initialItems)
109
110 // Verify the collection state contains our items
111 expect(collection.size).toBe(initialItems.length)
112 expect(collection.get(`1`)).toEqual(initialItems[0])
113 expect(collection.get(`2`)).toEqual(initialItems[1])
114
115 // Verify the synced data
116 expect(collection._state.syncedData.size).toBe(initialItems.length)
117 expect(collection._state.syncedData.get(`1`)).toEqual(initialItems[0])
118 expect(collection._state.syncedData.get(`2`)).toEqual(initialItems[1])
119
120 await db.remove()
121 })
122
123 it(`should initialize and fetch initial data with many documents`, async () => {
124 const docsAmount = 25 // > 10 to force multiple batches
125 const initialItems = getTestData(docsAmount)
126 const { collection, db } = await createTestState(initialItems)
127
128 // All docs should be present after initial sync
129 expect(collection.size).toBe(docsAmount)
130 expect(collection._state.syncedData.size).toBe(docsAmount)
131
132 // Spot-check a few positions
133 expect(collection.get(`1`)).toEqual({ id: `1`, name: `Item 1` })
134 expect(collection.get(`10`)).toEqual({ id: `10`, name: `Item 10` })
135 expect(collection.get(`11`)).toEqual({ id: `11`, name: `Item 11` })
136 expect(collection.get(`25`)).toEqual({ id: `25`, name: `Item 25` })
137
138 // Ensure no gaps
139 for (let i = 1; i <= docsAmount; i++) {
140 expect(collection.has(String(i))).toBe(true)
141 }
142
143 await db.remove()
144 })
145
146 it(`should update the collection when RxDB changes data`, async () => {
147 const initialItems = getTestData(2)
148
149 const { collection, rxCollection, db } =
150 await createTestState(initialItems)
151
152 // inserts
153 const doc = await rxCollection.insert({ id: `3`, name: `inserted` })
154 expect(collection.get(`3`).name).toEqual(`inserted`)
155
156 // updates
157 await doc.getLatest().patch({ name: `updated` })
158 expect(collection.get(`3`).name).toEqual(`updated`)
159
160 // deletes
161 await doc.getLatest().remove()
162 expect(collection.get(`3`)).toEqual(undefined)
163
164 await db.remove()
165 })
166
167 it(`should update RxDB when the collection changes data`, async () => {
168 const initialItems = getTestData(2)
169
170 const { collection, rxCollection, db } =
171 await createTestState(initialItems)
172
173 // inserts
174 const tx = collection.insert({ id: `3`, name: `inserted` })
175 await tx.isPersisted.promise
176 let doc = await rxCollection.findOne(`3`).exec(true)
177 expect(doc.name).toEqual(`inserted`)
178
179 // updates
180 collection.update(`3`, (d) => {
181 d.name = `updated`
182 })
183 expect(collection.get(`3`).name).toEqual(`updated`)
184 await collection.stateWhenReady()
185 await rxCollection.database.requestIdlePromise()
186 doc = await rxCollection.findOne(`3`).exec(true)
187 expect(doc.name).toEqual(`updated`)
188
189 // deletes
190 collection.delete(`3`)
191 await rxCollection.database.requestIdlePromise()
192 const mustNotBeFound = await rxCollection.findOne(`3`).exec()
193 expect(mustNotBeFound).toEqual(null)
194
195 await db.remove()
196 })
197 })
198
199 describe(`lifecycle management`, () => {
200 it(`should call unsubscribe when collection is cleaned up`, async () => {
201 const { collection, rxCollection, db } = await createTestState()
202
203 await collection.cleanup()
204
205 const subs = getFromMapOrCreate(
206 OPEN_RXDB_SUBSCRIPTIONS,
207 rxCollection,
208 () => new Set()
209 )
210 expect(subs.size).toEqual(0)
211
212 await db.remove()
213 })
214
215 it(`should restart sync when collection is accessed after cleanup`, async () => {
216 const initialItems = getTestData(2)
217 const { collection, rxCollection, db } =
218 await createTestState(initialItems)
219
220 await collection.cleanup()
221 await flushPromises()
222 expect(collection.status).toBe(`cleaned-up`)
223
224 // insert into RxDB while cleaned-up
225 await rxCollection.insert({ id: `3`, name: `Item 3` })
226
227 // Access collection data to restart sync
228 const subscription = collection.subscribeChanges(() => {})
229
230 await collection.toArrayWhenReady()
231 expect(collection.get(`3`).name).toEqual(`Item 3`)
232
233 subscription.unsubscribe()
234 await db.remove()
235 })
236 })
237
238 /**
239 * Here we simulate having multiple browser tabs
240 * open where the data should still be in sync.
241 */
242 describe(`multi tab`, () => {
243 it(`should update the state accross instances`, async () => {
244 const dbid = dbNameId++
245 const db1 = await getDatababase([], dbid)
246 const db2 = await getDatababase(getTestData(2), dbid)
247
248 const col1 = createCollection(
249 rxdbCollectionOptions({
250 rxCollection: db1.test,
251 startSync: true,
252 })
253 )
254 const col2 = createCollection(
255 rxdbCollectionOptions({
256 rxCollection: db2.test,
257 startSync: true,
258 })
259 )
260 await col1.stateWhenReady()
261 await col2.stateWhenReady()
262
263 // tanstack-db writes
264 col1.insert({ id: `t1`, name: `t1` })
265 col2.insert({ id: `t2`, name: `t2` })
266 await db1.test.findOne(`t1`).exec(true)
267 await db1.test.findOne(`t2`).exec(true)
268 await db2.test.findOne(`t1`).exec(true)
269 await db2.test.findOne(`t2`).exec(true)
270 expect(col2.get(`t1`)).toBeTruthy()
271 expect(col1.get(`t2`)).toBeTruthy()
272
273 // RxDB writes
274 await db1.test.insert({ id: `rx1`, name: `rx1` })
275 await db2.test.insert({ id: `rx2`, name: `rx2` })
276 expect(col2.get(`rx1`)).toBeTruthy()
277 expect(col1.get(`rx2`)).toBeTruthy()
278
279 db1.remove()
280 db2.remove()
281 })
282 })
283
284 describe(`error handling`, () => {
285 it.skip(`should rollback the transaction on invalid data that does not match the RxCollection schema`, async () => {
286 const initialItems = getTestData(2)
287 const { collection, db } = await createTestState(initialItems)
288
289 // INSERT
290 await expect(async () => {
291 const tx = collection.insert({
292 id: `3`,
293 name: `invalid`,
294 foo: `bar`,
295 })
296 await tx.isPersisted.promise
297 }).rejects.toThrow(/schema validation error/)
298 expect(collection.has(`3`)).toBe(false)
299
300 // UPDATE
301 await expect(async () => {
302 const tx = collection.update(`2`, (d) => {
303 d.name = `invalid`
304 d.foo = `bar`
305 })
306 await tx.isPersisted.promise
307 }).rejects.toThrow(/schema validation error/)
308 expect(collection.get(`2`).name).toBe(`Item 2`)
309
310 await db.remove()
311 })
312 })
313})