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

node-persisted-collection.e2e.test.ts

282 lines7.6 KB

1import { mkdtempSync, rmSync } from 'node:fs'
2import { tmpdir } from 'node:os'
3import { join } from 'node:path'
4import { afterAll, afterEach, beforeAll } from 'vitest'
5import { BTreeIndex, createCollection } from '@tanstack/db'
6import BetterSqlite3 from 'better-sqlite3'
7import { createNodeSQLitePersistence, persistedCollectionOptions } from '../src'
8import {
9 captureSeedData,
10 generateSeedData,
11} from '../../db-collection-e2e/src/fixtures/seed-data'
12import { runPersistedCollectionConformanceSuite } from '../../db-sqlite-persistence-core/tests/contracts/persisted-collection-conformance-contract'
13import type { Collection } from '@tanstack/db'
14import type {
15 Comment,
16 E2ETestConfig,
17 Post,
18 User,
19} from '../../db-collection-e2e/src/types'
20​
21type PersistableRow = {
22 id: string
24​
25type NodePersistedCollectionTestConfig = E2ETestConfig
26type PersistedCollectionHarness<T extends PersistableRow> = {
27 collection: Collection<T, string | number>
28 seedPersisted: (rows: Array<T>) => Promise<void>
30​
31let config: NodePersistedCollectionTestConfig
32​
33function createPersistedCollection<T extends PersistableRow>(
34 database: InstanceType<typeof BetterSqlite3>,
35 id: string,
36 syncMode: `eager` | `on-demand`,
37): PersistedCollectionHarness<T> {
38 const persistence = createNodeSQLitePersistence({
39 database,
40 })
41 let seedTxSequence = 0
42 const seedPersisted = async (rows: Array<T>): Promise<void> => {
43 if (rows.length === 0) {
44 return
45 }
46 seedTxSequence++
47 await persistence.adapter.applyCommittedTx(
48 { kind: `eager`, collectionId: id },
49 {
50 txId: `seed-${id}-${seedTxSequence}`,
51 term: 1,
52 seq: seedTxSequence,
53 rowVersion: seedTxSequence,
54 mutations: rows.map((row) => ({
55 type: `insert` as const,
56 key: row.id,
57 value: row,
58 })),
59 },
60 )
61 }
62​
63 const collection = createCollection(
64 persistedCollectionOptions<T, string | number>({
65 id,
66 syncMode,
67 getKey: (item) => item.id,
68 persistence,
69 autoIndex: `eager`,
70 defaultIndexType: BTreeIndex,
71 }),
72 )
73​
74 return {
75 collection,
76 seedPersisted,
77 }
79​
80type PersistedTransactionHandle = {
81 isPersisted: {
82 promise: Promise<unknown>
83 }
85​
86async function waitForPersisted(
87 transaction: PersistedTransactionHandle,
88): Promise<void> {
89 await transaction.isPersisted.promise
91​
92async function seedCollection<T extends PersistableRow>(
93 collection: Collection<T, string | number>,
94 rows: Array<T>,
95): Promise<void> {
96 const tx = collection.insert(rows)
97 await waitForPersisted(tx)
99​
100async function insertRowIntoCollections<T extends PersistableRow>(
101 collections: ReadonlyArray<Collection<T, string | number>>,
102 row: T,
103): Promise<void> {
104 for (const collection of collections) {
105 const tx = collection.insert(row)
106 await waitForPersisted(tx)
107 }
109​
110async function updateRowAcrossCollections<T extends PersistableRow>(
111 collections: ReadonlyArray<Collection<T, string | number>>,
112 id: string,
113 updates: Partial<T>,
114): Promise<void> {
115 for (const collection of collections) {
116 if (!collection.has(id)) {
117 continue
118 }
119 const tx = collection.update(id, (draft) => {
120 Object.assign(draft, updates)
121 })
122 await waitForPersisted(tx)
123 }
125​
126async function deleteRowAcrossCollections<T extends PersistableRow>(
127 collections: ReadonlyArray<Collection<T, string | number>>,
128 id: string,
129): Promise<void> {
130 for (const collection of collections) {
131 if (!collection.has(id)) {
132 continue
133 }
134 const tx = collection.delete(id)
135 await waitForPersisted(tx)
136 }
138​
139beforeAll(async () => {
140 const tempDirectory = mkdtempSync(join(tmpdir(), `db-node-persisted-e2e-`))
141 const dbPath = join(tempDirectory, `state.sqlite`)
142 const suiteId = Date.now().toString(36)
143 const database = new BetterSqlite3(dbPath)
144 const seedData = generateSeedData()
145 const fixture = captureSeedData(seedData, {
146 registration:
147 'packages/node-db-sqlite-persistence/e2e/node-persisted-collection.e2e.test.ts',
148 provider: 'BetterSqlite3',
149 })
150​
151 const eagerUsers = createPersistedCollection<User>(
152 database,
153 `node-persisted-users-eager-${suiteId}`,
154 `eager`,
155 )
156 const eagerPosts = createPersistedCollection<Post>(
157 database,
158 `node-persisted-posts-eager-${suiteId}`,
159 `eager`,
160 )
161 const eagerComments = createPersistedCollection<Comment>(
162 database,
163 `node-persisted-comments-eager-${suiteId}`,
164 `eager`,
165 )
166​
167 const onDemandUsers = createPersistedCollection<User>(
168 database,
169 `node-persisted-users-ondemand-${suiteId}`,
170 `on-demand`,
171 )
172 const onDemandPosts = createPersistedCollection<Post>(
173 database,
174 `node-persisted-posts-ondemand-${suiteId}`,
175 `on-demand`,
176 )
177 const onDemandComments = createPersistedCollection<Comment>(
178 database,
179 `node-persisted-comments-ondemand-${suiteId}`,
180 `on-demand`,
181 )
182​
183 await Promise.all([
184 eagerUsers.collection.preload(),
185 eagerPosts.collection.preload(),
186 eagerComments.collection.preload(),
187 ])
188​
189 await seedCollection(eagerUsers.collection, seedData.users)
190 await seedCollection(eagerPosts.collection, seedData.posts)
191 await seedCollection(eagerComments.collection, seedData.comments)
192 await onDemandUsers.seedPersisted(seedData.users)
193 await onDemandPosts.seedPersisted(seedData.posts)
194 await onDemandComments.seedPersisted(seedData.comments)
195​
196 config = {
197 fixture,
198 collections: {
199 eager: {
200 users: eagerUsers.collection,
201 posts: eagerPosts.collection,
202 comments: eagerComments.collection,
203 },
204 onDemand: {
205 users: onDemandUsers.collection,
206 posts: onDemandPosts.collection,
207 comments: onDemandComments.collection,
208 },
209 },
210 mutations: {
211 insertUser: async (user) =>
212 insertRowIntoCollections(
213 [eagerUsers.collection, onDemandUsers.collection],
214 user,
215 ),
216 updateUser: async (id, updates) =>
217 updateRowAcrossCollections(
218 [eagerUsers.collection, onDemandUsers.collection],
219 id,
220 updates,
221 ),
222 deleteUser: async (id) =>
223 deleteRowAcrossCollections(
224 [eagerUsers.collection, onDemandUsers.collection],
225 id,
226 ),
227 insertPost: async (post) =>
228 insertRowIntoCollections(
229 [eagerPosts.collection, onDemandPosts.collection],
230 post,
231 ),
232 deletePost: async (id) =>
233 deleteRowAcrossCollections(
234 [eagerPosts.collection, onDemandPosts.collection],
235 id,
236 ),
237 },
238 setup: async () => {},
239 afterEach: async () => {
240 await Promise.all([
241 onDemandUsers.collection.cleanup(),
242 onDemandPosts.collection.cleanup(),
243 onDemandComments.collection.cleanup(),
244 ])
245​
246 onDemandUsers.collection.startSyncImmediate()
247 onDemandPosts.collection.startSyncImmediate()
248 onDemandComments.collection.startSyncImmediate()
249 },
250 teardown: async () => {
251 await Promise.all([
252 eagerUsers.collection.cleanup(),
253 eagerPosts.collection.cleanup(),
254 eagerComments.collection.cleanup(),
255 onDemandUsers.collection.cleanup(),
256 onDemandPosts.collection.cleanup(),
257 onDemandComments.collection.cleanup(),
258 ])
259 database.close()
260 rmSync(tempDirectory, { recursive: true, force: true })
261 },
262 }
263})
264​
265afterEach(async () => {
266 if (config.afterEach) {
267 await config.afterEach()
268 }
269})
270​
271afterAll(async () => {
272 await config.teardown()
273})
274​
275function getConfig(): Promise<NodePersistedCollectionTestConfig> {
276 return Promise.resolve(config)
278​
279runPersistedCollectionConformanceSuite(
280 `node persisted collection conformance`,
281 getConfig,