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

infinite-query-conformance.test.ts

267 lines6.7 KB

1/**
2 * Vue driver for the shared infinite-query conformance suite.
3 *
4 * The effect scope owns the hook, and `nextTick` defines Vue's observation cut.
5 * Sources and query operators stay in this package's module realm. The shared
6 * suite, not this bridge, owns the ordered-prefix and page-ledger model.
7 */
8import {
9 BTreeIndex,
10 createCollection,
11 createLiveQueryCollection,
12 createLiveQueryWindowController,
13 gt,
14} from '@tanstack/db'
15import {
16 effectScope,
17 nextTick,
18 onScopeDispose,
19 reactive,
20 ref,
21 shallowRef,
22} from 'vue'
23import { describe, expect, it } from 'vitest'
24import { mockSyncCollectionOptions } from '../../db/tests/utils'
25import { runInfiniteQuerySuite } from '../../db/tests/conformance/infinite-suite'
26import { makeInfiniteOnDemandSource } from '../../db/tests/conformance/infinite-on-demand'
27import { withScopeSetup } from '../../db/tests/conformance/scope-setup'
28import { useLiveInfiniteQuery } from '../src/useLiveInfiniteQuery'
29import type {
30 InfiniteQueryConfig,
31 InfiniteQueryDriver,
32 InfiniteQueryHandle,
33} from '../../db/tests/conformance/infinite-contract'
34import type {
35 QueryBuild,
36 SourceHandle,
37} from '../../db/tests/conformance/contract'
38​
39let sourceSequence = 0
40​
41function makeSource<T extends { id: string }>(
42 initialData: ReadonlyArray<T>,
43): SourceHandle<T> {
44 const collection = createCollection(
45 mockSyncCollectionOptions<T>({
46 autoIndex: `eager`,
47 id: `infinite-conformance-vue-${sourceSequence++}`,
48 getKey: (row) => row.id,
49 initialData: [...initialData],
50 }),
51 )
52 const write = (type: `insert` | `update` | `delete`, value: T) => {
53 collection.utils.begin()
54 collection.utils.write({ type, value })
55 collection.utils.commit()
56 }
57 return {
58 collection,
59 insert: (row) => write(`insert`, row),
60 update: (row) => write(`update`, row),
61 remove: (row) => write(`delete`, row),
62 }
64​
65function makePrecreated(build: QueryBuild) {
66 return {
67 collection: createLiveQueryCollection({ query: build as any }),
68 }
70​
71async function settle(): Promise<void> {
72 await nextTick()
73 await new Promise((resolve) => setTimeout(resolve, 0))
75​
76function runInScope<R>(fn: () => R) {
77 const scope = effectScope()
78 let result!: R
79 withScopeSetup(
80 () =>
81 scope.run(() => {
82 result = fn()
83 }),
84 () => scope.stop(),
85 )
86 return { result, scope }
88​
89function makeHandle(
90 result: any,
91 scope: ReturnType<typeof effectScope>,
92): InfiniteQueryHandle {
93 return {
94 current() {
95 return {
96 data: result.data.value,
97 pages: result.pages.value,
98 pageParams: result.pageParams.value,
99 hasNextPage: result.hasNextPage.value,
100 isFetchingNextPage: result.isFetchingNextPage.value,
101 error: result.error.value,
102 status: result.status.value,
103 collection: result.collection.value,
104 }
105 },
106 fetchNextPage: () => result.fetchNextPage(),
107 flush: settle,
108 async apply(fn) {
109 fn()
110 await settle()
111 },
112 unmount() {
113 scope.stop()
114 },
115 }
117​
118function mount(build: QueryBuild, config: InfiniteQueryConfig = {}) {
119 const { result, scope } = runInScope(() =>
120 useLiveInfiniteQuery(build as any, config as any),
121 )
122 return makeHandle(result, scope)
124​
125function mountControllable<P>(
126 build: (q: any, param: P) => any,
127 initial: P,
128 config: InfiniteQueryConfig = {},
129) {
130 const param = ref(initial) as { value: P }
131 const { result, scope } = runInScope(() =>
132 useLiveInfiniteQuery((q: any) => build(q, param.value), config as any, [
133 param,
134 ]),
135 )
136 const handle = makeHandle(result, scope)
137 return {
138 ...handle,
139 setParamSync(next: P) {
140 param.value = next
141 },
142 }
144​
145function mountCollection(collection: any, config: InfiniteQueryConfig = {}) {
146 const { result, scope } = runInScope(() =>
147 useLiveInfiniteQuery(collection, config as any),
148 )
149 return makeHandle(result, scope)
151​
152function mountCollectionControllable(
153 initial: any,
154 config: InfiniteQueryConfig = {},
155) {
156 const collection = shallowRef(initial)
157 const { result, scope } = runInScope(() =>
158 useLiveInfiniteQuery(collection, config as any),
159 )
160 const handle = makeHandle(result, scope)
161 return {
162 ...handle,
163 replaceCollectionSync(next: any) {
164 collection.value = next
165 },
166 }
168​
169function mountConfigControllable(
170 build: QueryBuild,
171 initial: InfiniteQueryConfig,
172) {
173 const config = reactive({ ...initial })
174 const { result, scope } = runInScope(() =>
175 useLiveInfiniteQuery(build as any, config as any),
176 )
177 const handle = makeHandle(result, scope)
178 return {
179 ...handle,
180 setConfigSync(next: InfiniteQueryConfig) {
181 delete config.pageSize
182 delete config.initialPageParam
183 Object.assign(config, next)
184 },
185 }
187​
188function mountInputControllable(
189 collection: any,
190 build: QueryBuild,
191 config: InfiniteQueryConfig = {},
192) {
193 const kind = ref<`collection` | `query`>(`collection`)
194 const { result, scope } = runInScope(() =>
195 useLiveInfiniteQuery(
196 (q: any) => (kind.value === `collection` ? collection : build(q)),
197 config as any,
198 [kind],
199 ),
200 )
201 const handle = makeHandle(result, scope)
202 return {
203 ...handle,
204 setInputKindSync(next: `collection` | `query`) {
205 kind.value = next
206 },
207 }
209​
210const vueInfiniteDriver: InfiniteQueryDriver = {
211 name: `vue`,
212 gt,
213 makeSource,
214 makeOnDemandSource: (data, delay) =>
215 makeInfiniteOnDemandSource({ createCollection, BTreeIndex }, data, delay),
216 makePrecreated,
217 makeWindowController: createLiveQueryWindowController,
218 mount,
219 mountControllable,
220 mountCollection,
221 mountCollectionControllable,
222 mountConfigControllable,
223 mountInputControllable,
224 knownGaps: [],
226​
227runInfiniteQuerySuite(vueInfiniteDriver)
228​
229describe(`infinite driver scope ownership`, () => {
230 it(`retains successful scope until its owner disposes`, () => {
231 let calls = 0
232 const { scope } = runInScope(() =>
233 onScopeDispose(() => {
234 calls++
235 }),
236 )
237 expect(calls).toBe(0)
238 scope.stop()
239 expect(calls).toBe(1)
240 })
241 it.each([false, true])(
242 `cleans failed setup, cleanupFails=%s`,
243 (cleanupFails) => {
244 const primary = new Error(`setup`)
245 const secondary = new Error(`cleanup`)
246 let calls = 0
247 let caught: unknown
248 try {
249 runInScope(() => {
250 onScopeDispose(() => {
251 calls++
252 if (cleanupFails) throw secondary
253 })
254 throw primary
255 })
256 } catch (error) {
257 caught = error
258 }
259 expect(calls).toBe(1)
260 if (cleanupFails) {
261 expect(caught).toBeInstanceOf(AggregateError)
262 expect((caught as AggregateError).errors).toEqual([primary, secondary])
263 expect((caught as AggregateError).cause).toBe(primary)
264 } else expect(caught).toBe(primary)
265 },
266 )
267})