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

query.test-d.ts

756 lines23.1 KB

1/* eslint-disable @typescript-eslint/require-await */
2import { describe, expectTypeOf, it } from 'vitest'
3import {
4 and,
5 createCollection,
6 createLiveQueryCollection,
7 eq,
8 gt,
9 parseLoadSubsetOptions,
10} from '@tanstack/db'
11import { QueryClient } from '@tanstack/query-core'
12import { z } from 'zod'
13import { queryCollectionOptions } from '../src/query'
14import type {
15 DataTag,
16 QueryFunctionContext,
17 QueryObserverOptions,
18} from '@tanstack/query-core'
19import type { QueryCollectionConfig, QueryCollectionUtils } from '../src/query'
20import type {
21 DeleteMutationFnParams,
22 InsertMutationFnParams,
23 LoadSubsetOptions,
24 UpdateMutationFnParams,
25} from '@tanstack/db'
26import type { OutputWithVirtual } from '../../db/tests/utils'
27​
28describe(`Query collection type resolution tests`, () => {
29 // Define test types
30 type ExplicitType = { id: string; explicit: boolean }
31​
32 // Create a mock QueryClient for tests
33 const queryClient = new QueryClient()
34​
35 it(`should prioritize explicit type in QueryCollectionConfig`, () => {
36 const options = queryCollectionOptions<ExplicitType>({
37 id: `test`,
38 queryClient,
39 queryKey: [`test`],
40 queryFn: () => Promise.resolve([]),
41 getKey: (item) => item.id,
42 })
43​
44 // The getKey function should have the resolved type
45 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
46 })
47​
48 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
49 const options = queryCollectionOptions<ExplicitType>({
50 id: `test`,
51 queryClient,
52 queryKey: [`test`],
53 queryFn: () => Promise.resolve([]),
54 getKey: (item) => item.id,
55 onInsert: (params) => {
56 // Verify that the mutation value has the correct type
57 expectTypeOf(
58 params.transaction.mutations[0].modified,
59 ).toEqualTypeOf<ExplicitType>()
60 return Promise.resolve()
61 },
62 onUpdate: (params) => {
63 // Verify that the mutation value has the correct type
64 expectTypeOf(
65 params.transaction.mutations[0].modified,
66 ).toEqualTypeOf<ExplicitType>()
67 return Promise.resolve()
68 },
69 onDelete: (params) => {
70 // Verify that the mutation value has the correct type
71 expectTypeOf(
72 params.transaction.mutations[0].original,
73 ).toEqualTypeOf<ExplicitType>()
74 return Promise.resolve()
75 },
76 })
77​
78 // Verify that the handlers are properly typed
79 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
80 [
81 InsertMutationFnParams<
82 ExplicitType,
83 string | number,
84 QueryCollectionUtils<ExplicitType>
85 >,
86 ]
87 >()
88​
89 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
90 [
91 UpdateMutationFnParams<
92 ExplicitType,
93 string | number,
94 QueryCollectionUtils<ExplicitType>
95 >,
96 ]
97 >()
98​
99 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
100 [
101 DeleteMutationFnParams<
102 ExplicitType,
103 string | number,
104 QueryCollectionUtils<ExplicitType>
105 >,
106 ]
107 >()
108 })
109​
110 it(`should create collection with explicit types`, () => {
111 // Define a user type
112 type UserType = {
113 id: string
114 name: string
115 age: number
116 email: string
117 active: boolean
118 }
119​
120 // Create query collection options with explicit type
121 const queryOptions = queryCollectionOptions<UserType>({
122 id: `test`,
123 queryClient,
124 queryKey: [`users`],
125 queryFn: () => Promise.resolve([]),
126 getKey: (item) => item.id,
127 })
128​
129 // Create a collection using the query options
130 const usersCollection = createCollection(queryOptions)
131​
132 // Test that the collection itself has the correct type
133 expectTypeOf(usersCollection.toArray).toMatchTypeOf<
134 Array<OutputWithVirtual<UserType>>
135 >()
136​
137 // Test that the getKey function has the correct parameter type
138 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
139 })
140​
141 it(`should infer types from Zod schema through query collection options to live query`, () => {
142 // Define a Zod schema for a user with basic field types
143 const userSchema = z.object({
144 id: z.string(),
145 name: z.string(),
146 age: z.number(),
147 email: z.string().email(),
148 active: z.boolean(),
149 })
150​
151 type UserType = z.infer<typeof userSchema>
152​
153 // Create query collection options with the schema
154 const queryOptions = queryCollectionOptions({
155 queryClient,
156 queryKey: [`users`],
157 queryFn: () => Promise.resolve([] as Array<UserType>),
158 schema: userSchema,
159 getKey: (item) => item.id,
160 })
161​
162 // Create a collection using the query options
163 const usersCollection = createCollection(queryOptions)
164​
165 // Create a live query collection that uses the users collection
166 const activeUsersQuery = createLiveQueryCollection({
167 query: (q) =>
168 q
169 .from({ user: usersCollection })
170 .where(({ user }) => eq(user.active, true))
171 .select(({ user }) => ({
172 id: user.id,
173 name: user.name,
174 age: user.age,
175 email: user.email,
176 isActive: user.active,
177 })),
178 })
179​
180 // Test that the query results have the correct inferred types
181 const results = activeUsersQuery.toArray
182 expectTypeOf(results).toMatchTypeOf<
183 Array<
184 OutputWithVirtual<{
185 id: string
186 name: string
187 age: number
188 email: string
189 isActive: boolean
190 }>
191 >
192 >()
193​
194 // Test that the collection itself has the correct type
195 expectTypeOf(usersCollection.toArray).toMatchTypeOf<
196 Array<OutputWithVirtual<UserType>>
197 >()
198​
199 // Test that we can access schema-inferred fields in the query with WHERE conditions
200 const ageFilterQuery = createLiveQueryCollection({
201 query: (q) =>
202 q
203 .from({ user: usersCollection })
204 .where(({ user }) => and(eq(user.active, true), gt(user.age, 18)))
205 .select(({ user }) => ({
206 id: user.id,
207 name: user.name,
208 age: user.age,
209 })),
210 })
211​
212 const ageFilterResults = ageFilterQuery.toArray
213 expectTypeOf(ageFilterResults).toMatchTypeOf<
214 Array<
215 OutputWithVirtual<{
216 id: string
217 name: string
218 age: number
219 }>
220 >
221 >()
222​
223 // Test that the getKey function has the correct parameter type
224 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
225 })
226​
227 describe(`QueryFn type inference`, () => {
228 interface TodoType {
229 id: string
230 title: string
231 completed: boolean
232 }
233​
234 it(`should infer types from queryFn return type`, () => {
235 const options = queryCollectionOptions({
236 queryClient,
237 queryKey: [`queryfn-inference`],
238 queryFn: async (): Promise<Array<TodoType>> => {
239 return [] as Array<TodoType>
240 },
241 getKey: (item) => item.id,
242 })
243​
244 // Should infer TodoType from queryFn
245 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
246 })
247​
248 it(`should throw a type error if explicit type does not match the inferred type from the queryFn`, () => {
249 interface UserType {
250 id: string
251 name: string
252 }
253​
254 queryCollectionOptions<UserType>({
255 queryClient,
256 queryKey: [`explicit-priority`],
257 // @ts-expect-error – queryFn doesn't match the explicit type
258 queryFn: async (): Promise<Array<TodoType>> => {
259 return [] as Array<TodoType>
260 },
261 getKey: (item) => item.id,
262 })
263 })
264​
265 it(`should prioritize schema over queryFn`, () => {
266 const userSchema = z.object({
267 id: z.string(),
268 name: z.string(),
269 email: z.string(),
270 })
271​
272 const options = queryCollectionOptions({
273 queryClient,
274 queryKey: [`schema-priority`],
275 queryFn: async (): Promise<Array<z.infer<typeof userSchema>>> => {
276 return [] as Array<z.infer<typeof userSchema>>
277 },
278 schema: userSchema,
279 getKey: (item) => item.id,
280 })
281​
282 // Should use schema type, not TodoType from queryFn
283 type ExpectedType = z.infer<typeof userSchema>
284 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
285 })
286​
287 it(`should throw an error if schema type doesn't match the queryFn type`, () => {
288 interface UserType {
289 id: string
290 name: string
291 }
292​
293 const userSchema = z.object({
294 id: z.string(),
295 name: z.string(),
296 email: z.string(),
297 })
298​
299 const options = queryCollectionOptions({
300 queryClient,
301 queryKey: [`schema-priority`],
302 queryFn: async () => {
303 return [] as Array<UserType>
304 },
305 // @ts-expect-error – queryFn doesn't match the schema type
306 schema: userSchema,
307 getKey: (item) => item.id,
308 })
309​
310 // Should use schema type, not TodoType from queryFn
311 type ExpectedType = z.infer<typeof userSchema>
312 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
313 })
314​
315 it(`should maintain backward compatibility with explicit types`, () => {
316 const options = queryCollectionOptions<TodoType>({
317 queryClient,
318 queryKey: [`backward-compat`],
319 queryFn: async () => [] as Array<TodoType>,
320 getKey: (item) => item.id,
321 })
322​
323 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
324 })
325​
326 it(`should work with collection creation`, () => {
327 const options = queryCollectionOptions({
328 queryClient,
329 queryKey: [`collection-test`],
330 queryFn: async (): Promise<Array<TodoType>> => {
331 return [] as Array<TodoType>
332 },
333 getKey: (item) => item.id,
334 })
335​
336 const collection = createCollection(options)
337 expectTypeOf(collection.toArray).toEqualTypeOf<
338 Array<OutputWithVirtual<TodoType, string>>
339 >()
340 })
341 })
342​
343 describe(`select type inference`, () => {
344 it(`queryFn type inference`, () => {
345 const dataSchema = z.object({
346 id: z.string(),
347 name: z.string(),
348 email: z.string(),
349 })
350​
351 const options = queryCollectionOptions({
352 queryClient,
353 queryKey: [`x-queryFn-infer`],
354 queryFn: async (): Promise<Array<z.infer<typeof dataSchema>>> => {
355 return [] as Array<z.infer<typeof dataSchema>>
356 },
357 schema: dataSchema,
358 getKey: (item) => item.id,
359 })
360​
361 type ExpectedType = z.infer<typeof dataSchema>
362 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
363 })
364​
365 it(`should error when queryFn returns wrapped data without select`, () => {
366 const userData = z.object({
367 id: z.string(),
368 name: z.string(),
369 email: z.string(),
370 })
371​
372 type UserDataType = z.infer<typeof userData>
373​
374 type WrappedResponse = {
375 metadata: string
376 data: Array<UserDataType>
377 }
378​
379 queryCollectionOptions({
380 queryClient,
381 queryKey: [`wrapped-no-select`],
382 // @ts-expect-error - queryFn returns wrapped data but no select provided
383 queryFn: (): Promise<WrappedResponse> => {
384 return Promise.resolve({
385 metadata: `example`,
386 data: [],
387 })
388 },
389 // @ts-expect-error - schema type conflicts with queryFn return type
390 schema: userData,
391 // @ts-expect-error - item type is inferred as object due to type mismatch
392 getKey: (item) => item.id,
393 })
394 })
395​
396 it(`select properly extracts array from wrapped response`, () => {
397 const userData = z.object({
398 id: z.string(),
399 name: z.string(),
400 email: z.string(),
401 })
402​
403 type UserDataType = z.infer<typeof userData>
404​
405 type MetaDataType<T> = {
406 metaDataOne: string
407 metaDataTwo: string
408 data: T
409 }
410​
411 const metaDataObject: ResponseType = {
412 metaDataOne: `example meta data`,
413 metaDataTwo: `example meta data`,
414 data: [
415 {
416 id: `1`,
417 name: `carter`,
418 email: `c@email.com`,
419 },
420 ],
421 }
422​
423 type ResponseType = MetaDataType<Array<UserDataType>>
424​
425 const selectUserData = (data: ResponseType) => {
426 return data.data
427 }
428​
429 queryCollectionOptions({
430 queryClient,
431 queryKey: [`x-queryFn-infer`],
432 queryFn: async (): Promise<ResponseType> => {
433 return metaDataObject
434 },
435 select: selectUserData,
436 schema: userData,
437 getKey: (item) => item.id,
438 })
439​
440 // Should infer ResponseType as select parameter type
441 expectTypeOf(selectUserData).parameters.toEqualTypeOf<[ResponseType]>()
442 })
443 })
444​
445 describe(`loadSubsetOptions type inference`, () => {
446 interface TestItem {
447 id: string
448 name: string
449 }
450​
451 it(`should type loadSubsetOptions as LoadSubsetOptions in queryFn`, () => {
452 const config: QueryCollectionConfig<TestItem> = {
453 id: `loadSubsetTest`,
454 queryClient,
455 queryKey: [`loadSubsetTest`],
456 queryFn: (ctx) => {
457 // Verify that loadSubsetOptions is assignable to LoadSubsetOptions
458 // This ensures it can be used where LoadSubsetOptions is expected
459 expectTypeOf(
460 ctx.meta!.loadSubsetOptions!,
461 ).toExtend<LoadSubsetOptions>()
462 // so that parseLoadSubsetOptions can be called without type errors
463 parseLoadSubsetOptions(ctx.meta?.loadSubsetOptions)
464 // The fact that this call compiles without errors verifies that
465 // ctx.meta.loadSubsetOptions is typed correctly as LoadSubsetOptions
466 return Promise.resolve([])
467 },
468 getKey: (item) => item.id,
469 syncMode: `on-demand`,
470 }
471​
472 const options = queryCollectionOptions(config)
473 createCollection(options)
474 })
475​
476 it(`should allow meta to contain additional properties beyond loadSubsetOptions`, () => {
477 const config: QueryCollectionConfig<TestItem> = {
478 id: `loadSubsetTest`,
479 queryClient,
480 queryKey: [`loadSubsetTest`],
481 queryFn: (ctx) => {
482 // Verify that an object with loadSubsetOptions plus other properties
483 // can be assigned to ctx.meta's type. This ensures the type is not too restrictive.
484 const metaWithExtra = {
485 loadSubsetOptions: ctx.meta!.loadSubsetOptions!,
486 customProperty: `test`,
487 anotherProperty: 123,
488 }
489​
490 // Test that this object can be assigned to ctx.meta's type
491 // This verifies that ctx.meta allows additional properties beyond loadSubsetOptions
492 const typedMeta: typeof ctx.meta = metaWithExtra
493​
494 // Verify the assignment worked (this will fail at compile time if types don't match)
495 expectTypeOf(
496 typedMeta.loadSubsetOptions!,
497 ).toExtend<LoadSubsetOptions>()
498​
499 return Promise.resolve([])
500 },
501 getKey: (item) => item.id,
502 syncMode: `on-demand`,
503 }
504​
505 const options = queryCollectionOptions(config)
506 createCollection(options)
507 })
508​
509 it(`should have loadSubsetOptions typed automatically without explicit QueryCollectionMeta import`, () => {
510 // This test validates that the module augmentation works automatically
511 // Note: We are NOT importing QueryCollectionMeta, yet ctx.meta.loadSubsetOptions
512 // should still be properly typed as LoadSubsetOptions
513 const config: QueryCollectionConfig<TestItem> = {
514 id: `autoTypeTest`,
515 queryClient,
516 queryKey: [`autoTypeTest`],
517 queryFn: (ctx) => {
518 // This should compile without errors because the module augmentation
519 // in global.d.ts is automatically loaded via the triple-slash reference
520 // in index.ts
521 const options = ctx.meta?.loadSubsetOptions
522​
523 // Verify the type is correct
524 expectTypeOf(options).toMatchTypeOf<LoadSubsetOptions | undefined>()
525​
526 // Verify it can be passed to parseLoadSubsetOptions without type errors
527 const parsed = parseLoadSubsetOptions(options)
528 expectTypeOf(parsed).toMatchTypeOf<{
529 filters: Array<any>
530 sorts: Array<any>
531 limit?: number
532 }>()
533​
534 return Promise.resolve([])
535 },
536 getKey: (item) => item.id,
537 syncMode: `on-demand`,
538 }
539​
540 const options = queryCollectionOptions(config)
541 createCollection(options)
542 })
543​
544 it(`should allow users to extend QueryCollectionMeta via module augmentation`, () => {
545 // This test validates that users can extend QueryCollectionMeta to add custom properties
546 // by augmenting the @tanstack/query-db-collection module
547​
548 // In reality, users would do:
549 // declare module "@tanstack/query-db-collection" {
550 // interface QueryCollectionMeta {
551 // customUserId: number
552 // customContext?: string
553 // }
554 // }
555​
556 const config: QueryCollectionConfig<TestItem> = {
557 id: `extendMetaTest`,
558 queryClient,
559 queryKey: [`extendMetaTest`],
560 queryFn: (ctx) => {
561 // ctx.meta still has loadSubsetOptions
562 expectTypeOf(ctx.meta?.loadSubsetOptions).toMatchTypeOf<
563 LoadSubsetOptions | undefined
564 >()
565​
566 // This test documents the extension pattern even though we can't
567 // actually augment QueryCollectionMeta in a test file (it would
568 // affect all other tests in the same compilation unit)
569​
570 return Promise.resolve([])
571 },
572 getKey: (item) => item.id,
573 syncMode: `on-demand`,
574 }
575​
576 const options = queryCollectionOptions(config)
577 createCollection(options)
578 })
579 })
580​
581 describe(`queryOptions interoperability`, () => {
582 type NumberItem = {
583 id: number
584 value: string
585 }
586 type TaggedNumbersKey = DataTag<Array<string>, Array<NumberItem>, Error>
587 type NumberQueryObserverOptions = QueryObserverOptions<
588 Array<NumberItem>,
589 Error,
590 Array<NumberItem>,
591 Array<NumberItem>,
592 TaggedNumbersKey
593 >
594 const taggedNumbersQueryKey = [
595 `query-options-numbers`,
596 ] as unknown as TaggedNumbersKey
597​
598 it(`should accept queryOptions-like spread config with tagged queryKey`, () => {
599 const queryOptionsLike = {
600 queryKey: taggedNumbersQueryKey,
601 queryFn: () =>
602 Promise.resolve([
603 { id: 1, value: `one` },
604 { id: 2, value: `two` },
605 ]),
606 } satisfies {
607 queryKey: TaggedNumbersKey
608 queryFn?: NumberQueryObserverOptions[`queryFn`]
609 }
610​
611 const options = queryCollectionOptions({
612 ...queryOptionsLike,
613 queryClient,
614 getKey: (item) => item.id,
615 })
616​
617 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
618 })
619​
620 it(`should accept enabled from queryOptions-like config`, () => {
621 const queryOptionsLike = {
622 queryKey: taggedNumbersQueryKey,
623 queryFn: () => Promise.resolve([{ id: 1, value: `one` }]),
624 enabled: (_query) => true,
625 } satisfies {
626 queryKey: TaggedNumbersKey
627 queryFn?: NumberQueryObserverOptions[`queryFn`]
628 enabled?: NumberQueryObserverOptions[`enabled`]
629 }
630​
631 const options = queryCollectionOptions({
632 ...queryOptionsLike,
633 queryClient,
634 getKey: (item) => item.id,
635 })
636​
637 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
638 })
639​
640 it(`should require explicit queryFn when source type marks queryFn optional`, () => {
641 const queryOptionsLike: {
642 queryKey: TaggedNumbersKey
643 queryFn?: (
644 context: QueryFunctionContext<TaggedNumbersKey>,
645 ) => Array<NumberItem> | Promise<Array<NumberItem>>
646 } = {
647 queryKey: taggedNumbersQueryKey,
648 queryFn: () => Promise.resolve([{ id: 1, value: `one` }]),
649 }
650​
651 // @ts-expect-error - interop configs require queryFn even when source type marks it optional
652 queryCollectionOptions({
653 ...queryOptionsLike,
654 queryClient,
655 getKey: (item) => item.id,
656 })
657​
658 const options = queryCollectionOptions({
659 ...queryOptionsLike,
660 queryFn: (context) => queryOptionsLike.queryFn!(context),
661 queryClient,
662 getKey: (item) => item.id,
663 })
664​
665 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
666 })
667​
668 it(`should require select for wrapped queryOptions-like responses`, () => {
669 type WrappedResponse = {
670 total: number
671 items: Array<NumberItem>
672 }
673 type TaggedWrappedKey = DataTag<Array<string>, WrappedResponse, Error>
674 type WrappedObserverOptions = QueryObserverOptions<
675 WrappedResponse,
676 Error,
677 WrappedResponse,
678 WrappedResponse,
679 TaggedWrappedKey
680 >
681 const taggedWrappedQueryKey = [
682 `query-options-wrapped`,
683 ] as unknown as TaggedWrappedKey
684​
685 const wrappedQueryOptionsLike = {
686 queryKey: taggedWrappedQueryKey,
687 queryFn: () =>
688 Promise.resolve({
689 total: 1,
690 items: [{ id: 1, value: `one` }],
691 }),
692 } satisfies {
693 queryKey: TaggedWrappedKey
694 queryFn?: WrappedObserverOptions[`queryFn`]
695 }
696​
697 // @ts-expect-error - wrapped response requires select to extract the item array
698 queryCollectionOptions({
699 ...wrappedQueryOptionsLike,
700 queryClient,
701 getKey: () => 1,
702 })
703​
704 const options = queryCollectionOptions({
705 ...wrappedQueryOptionsLike,
706 select: (response) => response.items,
707 queryClient,
708 getKey: (item) => item.id,
709 })
710​
711 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
712 })
713​
714 it(`should still require queryFn for plain configs`, () => {
715 // @ts-expect-error - queryFn is required for plain configs
716 queryCollectionOptions<NumberItem>({
717 queryClient,
718 queryKey: [`query-options-missing-query-fn`],
719 getKey: (item) => item.id,
720 })
721 })
722​
723 it(`should accept synchronous queryFn return values`, () => {
724 const options = queryCollectionOptions<NumberItem>({
725 queryClient,
726 queryKey: [`query-options-sync-query-fn`],
727 queryFn: () => [{ id: 1, value: `one` }],
728 getKey: (item) => item.id,
729 })
730​
731 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[NumberItem]>()
732 })
733 })
734​
735 it(`should type collection.utils as QueryCollectionUtils after createCollection`, () => {
736 const collection = createCollection(
737 queryCollectionOptions<ExplicitType>({
738 id: `test-utils-typing`,
739 queryClient,
740 queryKey: [`test-utils`],
741 queryFn: () => Promise.resolve([]),
742 getKey: (item) => item.id,
743 }),
744 )
745​
746 // Verify that collection.utils is typed as QueryCollectionUtils, not UtilsRecord
747 const utils: QueryCollectionUtils<ExplicitType> = collection.utils
748 expectTypeOf(utils.refetch).toBeFunction()
749 expectTypeOf(collection.utils.refetch).toBeFunction()
750 expectTypeOf(collection.utils.writeInsert).toBeFunction()
751 expectTypeOf(collection.utils.writeUpdate).toBeFunction()
752 expectTypeOf(collection.utils.writeDelete).toBeFunction()
753 expectTypeOf(collection.utils.isFetching).toBeBoolean()
754 expectTypeOf(collection.utils.isLoading).toBeBoolean()
755 })
756})