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

rxdb.test.ts

326 lines9.7 KB

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