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

query.test-d.ts

277 lines8.3 KB

1import { describe, expectTypeOf, it } from "vitest"
2import {
3 createCollection,
4 createLiveQueryCollection,
5 eq,
6 gt,
7} from "@tanstack/db"
8import { QueryClient } from "@tanstack/query-core"
9import { z } from "zod"
10import { queryCollectionOptions } from "../src/query"
11import type {
12 DeleteMutationFnParams,
13 InsertMutationFnParams,
14 UpdateMutationFnParams,
15} from "@tanstack/db"
16​
17describe(`Query collection type resolution tests`, () => {
18 // Define test types
19 type ExplicitType = { id: string; explicit: boolean }
20​
21 // Create a mock QueryClient for tests
22 const queryClient = new QueryClient()
23​
24 it(`should prioritize explicit type in QueryCollectionConfig`, () => {
25 const options = queryCollectionOptions<ExplicitType>({
26 id: `test`,
27 queryClient,
28 queryKey: [`test`],
29 queryFn: () => Promise.resolve([]),
30 getKey: (item) => item.id,
31 })
32​
33 // The getKey function should have the resolved type
34 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
35 })
36​
37 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
38 const options = queryCollectionOptions<ExplicitType>({
39 id: `test`,
40 queryClient,
41 queryKey: [`test`],
42 queryFn: () => Promise.resolve([]),
43 getKey: (item) => item.id,
44 onInsert: (params) => {
45 // Verify that the mutation value has the correct type
46 expectTypeOf(
47 params.transaction.mutations[0].modified
48 ).toEqualTypeOf<ExplicitType>()
49 return Promise.resolve()
50 },
51 onUpdate: (params) => {
52 // Verify that the mutation value has the correct type
53 expectTypeOf(
54 params.transaction.mutations[0].modified
55 ).toEqualTypeOf<ExplicitType>()
56 return Promise.resolve()
57 },
58 onDelete: (params) => {
59 // Verify that the mutation value has the correct type
60 expectTypeOf(
61 params.transaction.mutations[0].original
62 ).toEqualTypeOf<ExplicitType>()
63 return Promise.resolve()
64 },
65 })
66​
67 // Verify that the handlers are properly typed
68 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
69 [InsertMutationFnParams<ExplicitType>]
70 >()
71​
72 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
73 [UpdateMutationFnParams<ExplicitType>]
74 >()
75​
76 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
77 [DeleteMutationFnParams<ExplicitType>]
78 >()
79 })
80​
81 it(`should create collection with explicit types`, () => {
82 // Define a user type
83 type UserType = {
84 id: string
85 name: string
86 age: number
87 email: string
88 active: boolean
89 }
90​
91 // Create query collection options with explicit type
92 const queryOptions = queryCollectionOptions<UserType>({
93 id: `test`,
94 queryClient,
95 queryKey: [`users`],
96 queryFn: () => Promise.resolve([]),
97 getKey: (item) => item.id,
98 })
99​
100 // Create a collection using the query options
101 const usersCollection = createCollection(queryOptions)
102​
103 // Test that the collection itself has the correct type
104 expectTypeOf(usersCollection.toArray).toEqualTypeOf<Array<UserType>>()
105​
106 // Test that the getKey function has the correct parameter type
107 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
108 })
109​
110 it(`should infer types from Zod schema through query collection options to live query`, () => {
111 // Define a Zod schema for a user with basic field types
112 const userSchema = z.object({
113 id: z.string(),
114 name: z.string(),
115 age: z.number(),
116 email: z.string().email(),
117 active: z.boolean(),
118 })
119​
120 type UserType = z.infer<typeof userSchema>
121​
122 // Create query collection options with the schema
123 const queryOptions = queryCollectionOptions({
124 queryClient,
125 queryKey: [`users`],
126 queryFn: () => Promise.resolve([] as Array<UserType>),
127 schema: userSchema,
128 getKey: (item) => item.id,
129 })
130​
131 // Create a collection using the query options
132 const usersCollection = createCollection(queryOptions)
133​
134 // Create a live query collection that uses the users collection
135 const activeUsersQuery = createLiveQueryCollection({
136 query: (q) =>
137 q
138 .from({ user: usersCollection })
139 .where(({ user }) => eq(user.active, true))
140 .select(({ user }) => ({
141 id: user.id,
142 name: user.name,
143 age: user.age,
144 email: user.email,
145 isActive: user.active,
146 })),
147 })
148​
149 // Test that the query results have the correct inferred types
150 const results = activeUsersQuery.toArray
151 expectTypeOf(results).toEqualTypeOf<
152 Array<{
153 id: string
154 name: string
155 age: number
156 email: string
157 isActive: boolean
158 }>
159 >()
160​
161 // Test that the collection itself has the correct type
162 expectTypeOf(usersCollection.toArray).toEqualTypeOf<Array<UserType>>()
163​
164 // Test that we can access schema-inferred fields in the query with WHERE conditions
165 const ageFilterQuery = createLiveQueryCollection({
166 query: (q) =>
167 q
168 .from({ user: usersCollection })
169 .where(({ user }) => eq(user.active, true) && gt(user.age, 18)) // eslint-disable-line @typescript-eslint/no-unnecessary-condition
170 .select(({ user }) => ({
171 id: user.id,
172 name: user.name,
173 age: user.age,
174 })),
175 })
176​
177 const ageFilterResults = ageFilterQuery.toArray
178 expectTypeOf(ageFilterResults).toEqualTypeOf<
179 Array<{
180 id: string
181 name: string
182 age: number
183 }>
184 >()
185​
186 // Test that the getKey function has the correct parameter type
187 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
188 })
189​
190 describe(`QueryFn type inference`, () => {
191 interface TodoType {
192 id: string
193 title: string
194 completed: boolean
195 }
196​
197 it(`should infer types from queryFn return type`, () => {
198 const options = queryCollectionOptions({
199 queryClient,
200 queryKey: [`queryfn-inference`],
201 queryFn: async (): Promise<Array<TodoType>> => {
202 return [] as Array<TodoType>
203 },
204 getKey: (item) => item.id,
205 })
206​
207 // Should infer TodoType from queryFn
208 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
209 })
210​
211 it(`should prioritize explicit type over queryFn`, () => {
212 interface UserType {
213 id: string
214 name: string
215 }
216​
217 const options = queryCollectionOptions<UserType>({
218 queryClient,
219 queryKey: [`explicit-priority`],
220 queryFn: async (): Promise<Array<TodoType>> => {
221 return [] as Array<TodoType>
222 },
223 getKey: (item) => item.id,
224 })
225​
226 // Should use explicit UserType, not TodoType from queryFn
227 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[UserType]>()
228 })
229​
230 it(`should prioritize schema over queryFn`, () => {
231 const userSchema = z.object({
232 id: z.string(),
233 name: z.string(),
234 email: z.string(),
235 })
236​
237 const options = queryCollectionOptions({
238 queryClient,
239 queryKey: [`schema-priority`],
240 queryFn: async (): Promise<Array<z.infer<typeof userSchema>>> => {
241 return [] as Array<z.infer<typeof userSchema>>
242 },
243 schema: userSchema,
244 getKey: (item) => item.id,
245 })
246​
247 // Should use schema type, not TodoType from queryFn
248 type ExpectedType = z.infer<typeof userSchema>
249 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
250 })
251​
252 it(`should maintain backward compatibility with explicit types`, () => {
253 const options = queryCollectionOptions<TodoType>({
254 queryClient,
255 queryKey: [`backward-compat`],
256 queryFn: async () => [] as Array<TodoType>,
257 getKey: (item) => item.id,
258 })
259​
260 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
261 })
262​
263 it(`should work with collection creation`, () => {
264 const options = queryCollectionOptions({
265 queryClient,
266 queryKey: [`collection-test`],
267 queryFn: async (): Promise<Array<TodoType>> => {
268 return [] as Array<TodoType>
269 },
270 getKey: (item) => item.id,
271 })
272​
273 const collection = createCollection(options)
274 expectTypeOf(collection.toArray).toEqualTypeOf<Array<TodoType>>()
275 })
276 })
277})