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

query.test-d.ts

406 lines11.8 KB

1import { describe, expectTypeOf, it } from "vitest"
2import {
3 and,
4 createCollection,
5 createLiveQueryCollection,
6 eq,
7 gt,
8} from "@tanstack/db"
9import { QueryClient } from "@tanstack/query-core"
10import { z } from "zod"
11import { queryCollectionOptions } from "../src/query"
12import type {
13 DeleteMutationFnParams,
14 InsertMutationFnParams,
15 UpdateMutationFnParams,
16} from "@tanstack/db"
17​
18describe(`Query collection type resolution tests`, () => {
19 // Define test types
20 type ExplicitType = { id: string; explicit: boolean }
21​
22 // Create a mock QueryClient for tests
23 const queryClient = new QueryClient()
24​
25 it(`should prioritize explicit type in QueryCollectionConfig`, () => {
26 const options = queryCollectionOptions<ExplicitType>({
27 id: `test`,
28 queryClient,
29 queryKey: [`test`],
30 queryFn: () => Promise.resolve([]),
31 getKey: (item) => item.id,
32 })
33​
34 // The getKey function should have the resolved type
35 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExplicitType]>()
36 })
37​
38 it(`should properly type the onInsert, onUpdate, and onDelete handlers`, () => {
39 const options = queryCollectionOptions<ExplicitType>({
40 id: `test`,
41 queryClient,
42 queryKey: [`test`],
43 queryFn: () => Promise.resolve([]),
44 getKey: (item) => item.id,
45 onInsert: (params) => {
46 // Verify that the mutation value has the correct type
47 expectTypeOf(
48 params.transaction.mutations[0].modified
49 ).toEqualTypeOf<ExplicitType>()
50 return Promise.resolve()
51 },
52 onUpdate: (params) => {
53 // Verify that the mutation value has the correct type
54 expectTypeOf(
55 params.transaction.mutations[0].modified
56 ).toEqualTypeOf<ExplicitType>()
57 return Promise.resolve()
58 },
59 onDelete: (params) => {
60 // Verify that the mutation value has the correct type
61 expectTypeOf(
62 params.transaction.mutations[0].original
63 ).toEqualTypeOf<ExplicitType>()
64 return Promise.resolve()
65 },
66 })
67​
68 // Verify that the handlers are properly typed
69 expectTypeOf(options.onInsert).parameters.toEqualTypeOf<
70 [InsertMutationFnParams<ExplicitType>]
71 >()
72​
73 expectTypeOf(options.onUpdate).parameters.toEqualTypeOf<
74 [UpdateMutationFnParams<ExplicitType>]
75 >()
76​
77 expectTypeOf(options.onDelete).parameters.toEqualTypeOf<
78 [DeleteMutationFnParams<ExplicitType>]
79 >()
80 })
81​
82 it(`should create collection with explicit types`, () => {
83 // Define a user type
84 type UserType = {
85 id: string
86 name: string
87 age: number
88 email: string
89 active: boolean
90 }
91​
92 // Create query collection options with explicit type
93 const queryOptions = queryCollectionOptions<UserType>({
94 id: `test`,
95 queryClient,
96 queryKey: [`users`],
97 queryFn: () => Promise.resolve([]),
98 getKey: (item) => item.id,
99 })
100​
101 // Create a collection using the query options
102 const usersCollection = createCollection(queryOptions)
103​
104 // Test that the collection itself has the correct type
105 expectTypeOf(usersCollection.toArray).toEqualTypeOf<Array<UserType>>()
106​
107 // Test that the getKey function has the correct parameter type
108 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
109 })
110​
111 it(`should infer types from Zod schema through query collection options to live query`, () => {
112 // Define a Zod schema for a user with basic field types
113 const userSchema = z.object({
114 id: z.string(),
115 name: z.string(),
116 age: z.number(),
117 email: z.string().email(),
118 active: z.boolean(),
119 })
120​
121 type UserType = z.infer<typeof userSchema>
122​
123 // Create query collection options with the schema
124 const queryOptions = queryCollectionOptions({
125 queryClient,
126 queryKey: [`users`],
127 queryFn: () => Promise.resolve([] as Array<UserType>),
128 schema: userSchema,
129 getKey: (item) => item.id,
130 })
131​
132 // Create a collection using the query options
133 const usersCollection = createCollection(queryOptions)
134​
135 // Create a live query collection that uses the users collection
136 const activeUsersQuery = createLiveQueryCollection({
137 query: (q) =>
138 q
139 .from({ user: usersCollection })
140 .where(({ user }) => eq(user.active, true))
141 .select(({ user }) => ({
142 id: user.id,
143 name: user.name,
144 age: user.age,
145 email: user.email,
146 isActive: user.active,
147 })),
148 })
149​
150 // Test that the query results have the correct inferred types
151 const results = activeUsersQuery.toArray
152 expectTypeOf(results).toEqualTypeOf<
153 Array<{
154 id: string
155 name: string
156 age: number
157 email: string
158 isActive: boolean
159 }>
160 >()
161​
162 // Test that the collection itself has the correct type
163 expectTypeOf(usersCollection.toArray).toEqualTypeOf<Array<UserType>>()
164​
165 // Test that we can access schema-inferred fields in the query with WHERE conditions
166 const ageFilterQuery = createLiveQueryCollection({
167 query: (q) =>
168 q
169 .from({ user: usersCollection })
170 .where(({ user }) => and(eq(user.active, true), gt(user.age, 18)))
171 .select(({ user }) => ({
172 id: user.id,
173 name: user.name,
174 age: user.age,
175 })),
176 })
177​
178 const ageFilterResults = ageFilterQuery.toArray
179 expectTypeOf(ageFilterResults).toEqualTypeOf<
180 Array<{
181 id: string
182 name: string
183 age: number
184 }>
185 >()
186​
187 // Test that the getKey function has the correct parameter type
188 expectTypeOf(queryOptions.getKey).parameters.toEqualTypeOf<[UserType]>()
189 })
190​
191 describe(`QueryFn type inference`, () => {
192 interface TodoType {
193 id: string
194 title: string
195 completed: boolean
196 }
197​
198 it(`should infer types from queryFn return type`, () => {
199 const options = queryCollectionOptions({
200 queryClient,
201 queryKey: [`queryfn-inference`],
202 queryFn: async (): Promise<Array<TodoType>> => {
203 return [] as Array<TodoType>
204 },
205 getKey: (item) => item.id,
206 })
207​
208 // Should infer TodoType from queryFn
209 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
210 })
211​
212 it(`should throw a type error if explicit type does not match the inferred type from the queryFn`, () => {
213 interface UserType {
214 id: string
215 name: string
216 }
217​
218 queryCollectionOptions<UserType>({
219 queryClient,
220 queryKey: [`explicit-priority`],
221 // @ts-expect-error – queryFn doesn't match the explicit type
222 queryFn: async (): Promise<Array<TodoType>> => {
223 return [] as Array<TodoType>
224 },
225 getKey: (item) => item.id,
226 })
227 })
228​
229 it(`should prioritize schema over queryFn`, () => {
230 const userSchema = z.object({
231 id: z.string(),
232 name: z.string(),
233 email: z.string(),
234 })
235​
236 const options = queryCollectionOptions({
237 queryClient,
238 queryKey: [`schema-priority`],
239 queryFn: async (): Promise<Array<z.infer<typeof userSchema>>> => {
240 return [] as Array<z.infer<typeof userSchema>>
241 },
242 schema: userSchema,
243 getKey: (item) => item.id,
244 })
245​
246 // Should use schema type, not TodoType from queryFn
247 type ExpectedType = z.infer<typeof userSchema>
248 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
249 })
250​
251 it(`should throw an error if schema type doesn't match the queryFn type`, () => {
252 interface UserType {
253 id: string
254 name: string
255 }
256​
257 const userSchema = z.object({
258 id: z.string(),
259 name: z.string(),
260 email: z.string(),
261 })
262​
263 const options = queryCollectionOptions({
264 queryClient,
265 queryKey: [`schema-priority`],
266 queryFn: async () => {
267 return [] as Array<UserType>
268 },
269 // @ts-expect-error – queryFn doesn't match the schema type
270 schema: userSchema,
271 getKey: (item) => item.id,
272 })
273​
274 // Should use schema type, not TodoType from queryFn
275 type ExpectedType = z.infer<typeof userSchema>
276 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
277 })
278​
279 it(`should maintain backward compatibility with explicit types`, () => {
280 const options = queryCollectionOptions<TodoType>({
281 queryClient,
282 queryKey: [`backward-compat`],
283 queryFn: async () => [] as Array<TodoType>,
284 getKey: (item) => item.id,
285 })
286​
287 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[TodoType]>()
288 })
289​
290 it(`should work with collection creation`, () => {
291 const options = queryCollectionOptions({
292 queryClient,
293 queryKey: [`collection-test`],
294 queryFn: async (): Promise<Array<TodoType>> => {
295 return [] as Array<TodoType>
296 },
297 getKey: (item) => item.id,
298 })
299​
300 const collection = createCollection(options)
301 expectTypeOf(collection.toArray).toEqualTypeOf<Array<TodoType>>()
302 })
303 })
304​
305 describe(`select type inference`, () => {
306 it(`queryFn type inference`, () => {
307 const dataSchema = z.object({
308 id: z.string(),
309 name: z.string(),
310 email: z.string(),
311 })
312​
313 const options = queryCollectionOptions({
314 queryClient,
315 queryKey: [`x-queryFn-infer`],
316 queryFn: async (): Promise<Array<z.infer<typeof dataSchema>>> => {
317 return [] as Array<z.infer<typeof dataSchema>>
318 },
319 schema: dataSchema,
320 getKey: (item) => item.id,
321 })
322​
323 type ExpectedType = z.infer<typeof dataSchema>
324 expectTypeOf(options.getKey).parameters.toEqualTypeOf<[ExpectedType]>()
325 })
326​
327 it(`should error when queryFn returns wrapped data without select`, () => {
328 const userData = z.object({
329 id: z.string(),
330 name: z.string(),
331 email: z.string(),
332 })
333​
334 type UserDataType = z.infer<typeof userData>
335​
336 type WrappedResponse = {
337 metadata: string
338 data: Array<UserDataType>
339 }
340​
341 queryCollectionOptions({
342 queryClient,
343 queryKey: [`wrapped-no-select`],
344 // @ts-expect-error - queryFn returns wrapped data but no select provided
345 queryFn: (): Promise<WrappedResponse> => {
346 return Promise.resolve({
347 metadata: `example`,
348 data: [],
349 })
350 },
351 // @ts-expect-error - schema type conflicts with queryFn return type
352 schema: userData,
353 // @ts-expect-error - item type is inferred as object due to type mismatch
354 getKey: (item) => item.id,
355 })
356 })
357​
358 it(`select properly extracts array from wrapped response`, () => {
359 const userData = z.object({
360 id: z.string(),
361 name: z.string(),
362 email: z.string(),
363 })
364​
365 type UserDataType = z.infer<typeof userData>
366​
367 type MetaDataType<T> = {
368 metaDataOne: string
369 metaDataTwo: string
370 data: T
371 }
372​
373 const metaDataObject: ResponseType = {
374 metaDataOne: `example meta data`,
375 metaDataTwo: `example meta data`,
376 data: [
377 {
378 id: `1`,
379 name: `carter`,
380 email: `c@email.com`,
381 },
382 ],
383 }
384​
385 type ResponseType = MetaDataType<Array<UserDataType>>
386​
387 const selectUserData = (data: ResponseType) => {
388 return data.data
389 }
390​
391 queryCollectionOptions({
392 queryClient,
393 queryKey: [`x-queryFn-infer`],
394 queryFn: async (): Promise<ResponseType> => {
395 return metaDataObject
396 },
397 select: selectUserData,
398 schema: userData,
399 getKey: (item) => item.id,
400 })
401​
402 // Should infer ResponseType as select parameter type
403 expectTypeOf(selectUserData).parameters.toEqualTypeOf<[ResponseType]>()
404 })
405 })
406})