Open History to see the last commit
1import { QueryClient } from '@tanstack/query-core'
2import { createKey } from '@tanstack/query-test-utils'
3import { describe, expectTypeOf, it } from 'vitest'
4import { createQueries, queryOptions } from '../../src/index.js'
5import type {
6 CreateQueryOptions,
7 CreateQueryResult,
8 QueryFunction,
9 QueryFunctionContext,
10 QueryKey,
11 skipToken,
12} from '../../src/index.js'
13β
14describe('createQueries', () => {
15 it('should return correct data for dynamic queries with mixed result types', () => {
16 const key1 = createKey()
17 const key2 = createKey()
18 const Queries1 = {
19 get: () =>
20 queryOptions({
21 queryKey: key1,
22 queryFn: () => Promise.resolve(1),
23 }),
24 }
25 const Queries2 = {
26 get: () =>
27 queryOptions({
28 queryKey: key2,
29 queryFn: () => Promise.resolve(true),
30 }),
31 }
32β
33 const queries1List = [1, 2, 3].map(() => ({ ...Queries1.get() }))
34 const result = createQueries(() => ({
35 queries: [...queries1List, { ...Queries2.get() }],
36 }))
37β
38 expectTypeOf(result).toEqualTypeOf<
39 [
40 ...Array<CreateQueryResult<number, Error>>,
41 CreateQueryResult<boolean, Error>,
42 ]
43 >()
44 })
45β
46 it('should handle type parameter - tuple of tuples', () => {
47 const queryClient = new QueryClient()
48 const key1 = createKey()
49 const key2 = createKey()
50 const key3 = createKey()
51β
52 const result1 = createQueries<
53 [[number], [string], [Array<string>, boolean]]
54 >(
55 () => ({
56 queries: [
57 {
58 queryKey: key1,
59 queryFn: () => 1,
60 },
61 {
62 queryKey: key2,
63 queryFn: () => 'string',
64 },
65 {
66 queryKey: key3,
67 queryFn: () => ['string[]'],
68 },
69 ],
70 }),
71 () => queryClient,
72 )
73β
74 expectTypeOf(result1[0]).toEqualTypeOf<CreateQueryResult<number, unknown>>()
75 expectTypeOf(result1[1]).toEqualTypeOf<CreateQueryResult<string, unknown>>()
76 expectTypeOf(result1[2]).toEqualTypeOf<
77 CreateQueryResult<Array<string>, boolean>
78 >()
79 expectTypeOf(result1[0].data).toEqualTypeOf<number | undefined>()
80 expectTypeOf(result1[1].data).toEqualTypeOf<string | undefined>()
81 expectTypeOf(result1[2].data).toEqualTypeOf<Array<string> | undefined>()
82 expectTypeOf(result1[2].error).toEqualTypeOf<boolean | null>()
83β
84 // TData (3rd element) takes precedence over TQueryFnData (1st element)
85 const result2 = createQueries<
86 [[string, unknown, string], [string, unknown, number]]
87 >(
88 () => ({
89 queries: [
90 {
91 queryKey: key1,
92 queryFn: () => 'string',
93 select: (a) => {
94 expectTypeOf(a).toEqualTypeOf<string>()
95 return a.toLowerCase()
96 },
97 },
98 {
99 queryKey: key2,
100 queryFn: () => 'string',
101 select: (a) => {
102 expectTypeOf(a).toEqualTypeOf<string>()
103 return parseInt(a)
104 },
105 },
106 ],
107 }),
108 () => queryClient,
109 )
110β
111 expectTypeOf(result2[0]).toEqualTypeOf<CreateQueryResult<string, unknown>>()
112 expectTypeOf(result2[1]).toEqualTypeOf<CreateQueryResult<number, unknown>>()
113 expectTypeOf(result2[0].data).toEqualTypeOf<string | undefined>()
114 expectTypeOf(result2[1].data).toEqualTypeOf<number | undefined>()
115β
116 // types should be enforced
117 createQueries<[[string, unknown, string], [string, boolean, number]]>(
118 () => ({
119 queries: [
120 {
121 queryKey: key1,
122 queryFn: () => 'string',
123 select: (a) => {
124 expectTypeOf(a).toEqualTypeOf<string>()
125 return a.toLowerCase()
126 },
127 placeholderData: 'string',
128 // @ts-expect-error (initialData: string)
129 initialData: 123,
130 },
131 {
132 queryKey: key2,
133 queryFn: () => 'string',
134 select: (a) => {
135 expectTypeOf(a).toEqualTypeOf<string>()
136 return parseInt(a)
137 },
138 placeholderData: 'string',
139 // @ts-expect-error (initialData: string)
140 initialData: 123,
141 },
142 ],
143 }),
144 () => queryClient,
145 )
146β
147 // field names should be enforced
148 createQueries<[[string]]>(
149 () => ({
150 queries: [
151 {
152 queryKey: key1,
153 queryFn: () => 'string',
154 },
155 ],
156 }),
157 () => queryClient,
158 )
159 })
160β
161 it('should handle type parameter - tuple of objects', () => {
162 const queryClient = new QueryClient()
163 const key1 = createKey()
164 const key2 = createKey()
165 const key3 = createKey()
166β
167 const result1 = createQueries<
168 [
169 { queryFnData: number },
170 { queryFnData: string },
171 { queryFnData: Array<string>; error: boolean },
172 ]
173 >(
174 () => ({
175 queries: [
176 {
177 queryKey: key1,
178 queryFn: () => 1,
179 },
180 {
181 queryKey: key2,
182 queryFn: () => 'string',
183 },
184 {
185 queryKey: key3,
186 queryFn: () => ['string[]'],
187 },
188 ],
189 }),
190 () => queryClient,
191 )
192β
193 expectTypeOf(result1[0]).toEqualTypeOf<CreateQueryResult<number, unknown>>()
194 expectTypeOf(result1[1]).toEqualTypeOf<CreateQueryResult<string, unknown>>()
195 expectTypeOf(result1[2]).toEqualTypeOf<
196 CreateQueryResult<Array<string>, boolean>
197 >()
198 expectTypeOf(result1[0].data).toEqualTypeOf<number | undefined>()
199 expectTypeOf(result1[1].data).toEqualTypeOf<string | undefined>()
200 expectTypeOf(result1[2].data).toEqualTypeOf<Array<string> | undefined>()
201 expectTypeOf(result1[2].error).toEqualTypeOf<boolean | null>()
202β
203 // TData (data prop) takes precedence over TQueryFnData (queryFnData prop)
204 const result2 = createQueries<
205 [
206 { queryFnData: string; data: string },
207 { queryFnData: string; data: number },
208 ]
209 >(
210 () => ({
211 queries: [
212 {
213 queryKey: key1,
214 queryFn: () => 'string',
215 select: (a) => {
216 expectTypeOf(a).toEqualTypeOf<string>()
217 return a.toLowerCase()
218 },
219 },
220 {
221 queryKey: key2,
222 queryFn: () => 'string',
223 select: (a) => {
224 expectTypeOf(a).toEqualTypeOf<string>()
225 return parseInt(a)
226 },
227 },
228 ],
229 }),
230 () => queryClient,
231 )
232β
233 expectTypeOf(result2[0]).toEqualTypeOf<CreateQueryResult<string, unknown>>()
234 expectTypeOf(result2[1]).toEqualTypeOf<CreateQueryResult<number, unknown>>()
235 expectTypeOf(result2[0].data).toEqualTypeOf<string | undefined>()
236 expectTypeOf(result2[1].data).toEqualTypeOf<number | undefined>()
237β
238 // can pass only TData (data prop) although TQueryFnData will be left unknown
239 const result3 = createQueries<[{ data: string }, { data: number }]>(
240 () => ({
241 queries: [
242 {
243 queryKey: key1,
244 queryFn: () => 'string',
245 select: (a) => {
246 expectTypeOf(a).toEqualTypeOf<unknown>()
247 return a as string
248 },
249 },
250 {
251 queryKey: key2,
252 queryFn: () => 'string',
253 select: (a) => {
254 expectTypeOf(a).toEqualTypeOf<unknown>()
255 return a as number
256 },
257 },
258 ],
259 }),
260 () => queryClient,
261 )
262β
263 expectTypeOf(result3[0]).toEqualTypeOf<CreateQueryResult<string, unknown>>()
264 expectTypeOf(result3[1]).toEqualTypeOf<CreateQueryResult<number, unknown>>()
265 expectTypeOf(result3[0].data).toEqualTypeOf<string | undefined>()
266 expectTypeOf(result3[1].data).toEqualTypeOf<number | undefined>()
267β
268 // types should be enforced
269 createQueries<
270 [
271 { queryFnData: string; data: string },
272 { queryFnData: string; data: number; error: boolean },
273 ]
274 >(
275 () => ({
276 queries: [
277 {
278 queryKey: key1,
279 queryFn: () => 'string',
280 select: (a) => {
281 expectTypeOf(a).toEqualTypeOf<string>()
282 return a.toLowerCase()
283 },
284 placeholderData: 'string',
285 // @ts-expect-error (initialData: string)
286 initialData: 123,
287 },
288 {
289 queryKey: key2,
290 queryFn: () => 'string',
291 select: (a) => {
292 expectTypeOf(a).toEqualTypeOf<string>()
293 return parseInt(a)
294 },
295 placeholderData: 'string',
296 // @ts-expect-error (initialData: string)
297 initialData: 123,
298 },
299 ],
300 }),
301 () => queryClient,
302 )
303β
304 // field names should be enforced
305 createQueries<[{ queryFnData: string }]>(
306 () => ({
307 queries: [
308 {
309 queryKey: key1,
310 queryFn: () => 'string',
311 },
312 ],
313 }),
314 () => queryClient,
315 )
316 })
317β
318 it('should handle array literal without type parameter to infer result type', () => {
319 const queryClient = new QueryClient()
320 const key1 = createKey()
321 const key2 = createKey()
322 const key3 = createKey()
323 const key4 = createKey()
324β
325 // Array.map preserves TQueryFnData
326 const result1 = createQueries(
327 () => ({
328 queries: Array(50).map((_, i) => ({
329 queryKey: ['key', i] as const,
330 queryFn: () => i + 10,
331 })),
332 }),
333 () => queryClient,
334 )
335β
336 expectTypeOf(result1).toEqualTypeOf<
337 Array<CreateQueryResult<number, Error>>
338 >()
339 if (result1[0]) {
340 expectTypeOf(result1[0].data).toEqualTypeOf<number | undefined>()
341 }
342β
343 // Array.map preserves TData
344 const result2 = createQueries(
345 () => ({
346 queries: Array(50).map((_, i) => ({
347 queryKey: ['key', i] as const,
348 queryFn: () => i + 10,
349 select: (data: number) => data.toString(),
350 })),
351 }),
352 () => queryClient,
353 )
354β
355 expectTypeOf(result2).toEqualTypeOf<
356 Array<CreateQueryResult<string, Error>>
357 >()
358β
359 const result3 = createQueries(
360 () => ({
361 queries: [
362 {
363 queryKey: key1,
364 queryFn: () => 1,
365 },
366 {
367 queryKey: key2,
368 queryFn: () => 'string',
369 },
370 {
371 queryKey: key3,
372 queryFn: () => ['string[]'],
373 select: () => 123,
374 },
375 ],
376 }),
377 () => queryClient,
378 )
379β
380 expectTypeOf(result3[0]).toEqualTypeOf<CreateQueryResult<number, Error>>()
381 expectTypeOf(result3[1]).toEqualTypeOf<CreateQueryResult<string, Error>>()
382 expectTypeOf(result3[2]).toEqualTypeOf<CreateQueryResult<number, Error>>()
383 expectTypeOf(result3[0].data).toEqualTypeOf<number | undefined>()
384 expectTypeOf(result3[1].data).toEqualTypeOf<string | undefined>()
385 // select takes precedence over queryFn
386 expectTypeOf(result3[2].data).toEqualTypeOf<number | undefined>()
387β
388 // initialData/placeholderData are enforced
389 createQueries(
390 () => ({
391 queries: [
392 {
393 queryKey: key1,
394 queryFn: () => 'string',
395 placeholderData: 'string',
396 // @ts-expect-error (initialData: string)
397 initialData: 123,
398 },
399 {
400 queryKey: key2,
401 queryFn: () => 123,
402 // @ts-expect-error (placeholderData: number)
403 placeholderData: 'string',
404 initialData: 123,
405 },
406 ],
407 }),
408 () => queryClient,
409 )
410β
411 // select params are "indirectly" enforced
412 createQueries(
413 () => ({
414 queries: [
415 // unfortunately TS will not suggest the type for you
416 {
417 queryKey: key1,
418 queryFn: () => 'string',
419 },
420 // however you can add a type to the callback
421 {
422 queryKey: key2,
423 queryFn: () => 'string',
424 },
425 // the type you do pass is enforced
426 {
427 queryKey: key3,
428 queryFn: () => 'string',
429 },
430 {
431 queryKey: key4,
432 queryFn: () => 'string',
433 select: (a: string) => parseInt(a),
434 },
435 ],
436 }),
437 () => queryClient,
438 )
439β
440 // callbacks are also indirectly enforced with Array.map
441 createQueries(
442 () => ({
443 queries: Array(50).map((_, i) => ({
444 queryKey: ['key', i] as const,
445 queryFn: () => i + 10,
446 select: (data: number) => data.toString(),
447 })),
448 }),
449 () => queryClient,
450 )
451β
452 // results inference works when all the handlers are defined
453 const result4 = createQueries(
454 () => ({
455 queries: [
456 {
457 queryKey: key1,
458 queryFn: () => 'string',
459 },
460 {
461 queryKey: key2,
462 queryFn: () => 'string',
463 },
464 {
465 queryKey: key4,
466 queryFn: () => 'string',
467 select: (a: string) => parseInt(a),
468 },
469 ],
470 }),
471 () => queryClient,
472 )
473β
474 expectTypeOf(result4[0]).toEqualTypeOf<CreateQueryResult<string, Error>>()
475 expectTypeOf(result4[1]).toEqualTypeOf<CreateQueryResult<string, Error>>()
476 expectTypeOf(result4[2]).toEqualTypeOf<CreateQueryResult<number, Error>>()
477β
478 // handles when queryFn returns a Promise
479 const result5 = createQueries(
480 () => ({
481 queries: [
482 {
483 queryKey: key1,
484 queryFn: () => Promise.resolve('string'),
485 },
486 ],
487 }),
488 () => queryClient,
489 )
490β
491 expectTypeOf(result5[0]).toEqualTypeOf<CreateQueryResult<string, Error>>()
492β
493 // Array as const does not throw error
494 const result6 = createQueries(
495 () =>
496 ({
497 queries: [
498 {
499 queryKey: ['key1'],
500 queryFn: () => 'string',
501 },
502 {
503 queryKey: ['key1'],
504 queryFn: () => 123,
505 },
506 ],
507 }) as const,
508 () => queryClient,
509 )
510β
511 expectTypeOf(result6[0]).toEqualTypeOf<CreateQueryResult<string, Error>>()
512 expectTypeOf(result6[1]).toEqualTypeOf<CreateQueryResult<number, Error>>()
513β
514 // field names should be enforced - array literal
515 createQueries(
516 () => ({
517 queries: [
518 {
519 queryKey: key1,
520 queryFn: () => 'string',
521 },
522 ],
523 }),
524 () => queryClient,
525 )
526β
527 // field names should be enforced - Array.map() result
528 createQueries(
529 () => ({
530 // @ts-expect-error (invalidField)
531 queries: Array(10).map(() => ({
532 someInvalidField: '',
533 })),
534 }),
535 () => queryClient,
536 )
537β
538 // supports queryFn using fetch() to return Promise<any> - Array.map() result
539 createQueries(
540 () => ({
541 queries: Array(50).map((_, i) => ({
542 queryKey: ['key', i] as const,
543 queryFn: () =>
544 fetch('return Promise<any>').then((resp) => resp.json()),
545 })),
546 }),
547 () => queryClient,
548 )
549β
550 // supports queryFn using fetch() to return Promise<any> - array literal
551 createQueries(
552 () => ({
553 queries: [
554 {
555 queryKey: key1,
556 queryFn: () =>
557 fetch('return Promise<any>').then((resp) => resp.json()),
558 },
559 ],
560 }),
561 () => queryClient,
562 )
563 })
564β
565 it('should handle strongly typed queryFn factories and createQueries wrappers', () => {
566 const queryClient = new QueryClient()
567β
568 // QueryKey + queryFn factory
569 type QueryKeyA = ['queryA']
570 const getQueryKeyA = (): QueryKeyA => ['queryA']
571 type GetQueryFunctionA = () => QueryFunction<number, QueryKeyA>
572 const getQueryFunctionA: GetQueryFunctionA = () => () => {
573 return 1
574 }
575 type SelectorA = (data: number) => [number, string]
576 const getSelectorA = (): SelectorA => (data) => [data, data.toString()]
577β
578 type QueryKeyB = ['queryB', string]
579 const getQueryKeyB = (id: string): QueryKeyB => ['queryB', id]
580 type GetQueryFunctionB = () => QueryFunction<string, QueryKeyB>
581 const getQueryFunctionB: GetQueryFunctionB = () => () => {
582 return '1'
583 }
584 type SelectorB = (data: string) => [string, number]
585 const getSelectorB = (): SelectorB => (data) => [data, +data]
586β
587 // Wrapper with strongly typed array-parameter
588 function useWrappedQueries<
589 TQueryFnData,
590 TError,
591 TData,
592 TQueryKey extends QueryKey,
593 >(
594 queries: Array<
595 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>
596 >,
597 ) {
598 return createQueries(
599 () => ({
600 queries: queries.map(
601 // no need to type the mapped query
602 (query) => {
603 const { queryFn: fn, queryKey: key } = query
604 expectTypeOf(fn).toEqualTypeOf<
605 | typeof skipToken
606 | QueryFunction<TQueryFnData, TQueryKey, never>
607 | undefined
608 >()
609 return {
610 queryKey: key,
611 queryFn: fn
612 ? (ctx: QueryFunctionContext<TQueryKey>) => {
613 // oxlint-disable-next-line vitest-js/valid-expect -- matchers cannot compare against an unresolved type parameter, so the type argument checks that 'ctx.queryKey' is assignable to 'TQueryKey'
614 expectTypeOf<TQueryKey>(ctx.queryKey)
615 return (
616 fn as QueryFunction<TQueryFnData, TQueryKey>
617 ).call({}, ctx)
618 }
619 : undefined,
620 }
621 },
622 ),
623 }),
624 () => queryClient,
625 )
626 }
627β
628 const result = createQueries(
629 () => ({
630 queries: [
631 {
632 queryKey: getQueryKeyA(),
633 queryFn: getQueryFunctionA(),
634 },
635 {
636 queryKey: getQueryKeyB('id'),
637 queryFn: getQueryFunctionB(),
638 },
639 ],
640 }),
641 () => queryClient,
642 )
643β
644 expectTypeOf(result[0]).toEqualTypeOf<CreateQueryResult<number, Error>>()
645 expectTypeOf(result[1]).toEqualTypeOf<CreateQueryResult<string, Error>>()
646β
647 const withSelector = createQueries(
648 () => ({
649 queries: [
650 {
651 queryKey: getQueryKeyA(),
652 queryFn: getQueryFunctionA(),
653 select: getSelectorA(),
654 },
655 {
656 queryKey: getQueryKeyB('id'),
657 queryFn: getQueryFunctionB(),
658 select: getSelectorB(),
659 },
660 ],
661 }),
662 () => queryClient,
663 )
664β
665 expectTypeOf(withSelector[0]).toEqualTypeOf<
666 CreateQueryResult<[number, string], Error>
667 >()
668 expectTypeOf(withSelector[1]).toEqualTypeOf<
669 CreateQueryResult<[string, number], Error>
670 >()
671β
672 const withWrappedQueries = useWrappedQueries(
673 Array(10).map(() => ({
674 queryKey: getQueryKeyA(),
675 queryFn: getQueryFunctionA(),
676 select: getSelectorA(),
677 })),
678 )
679β
680 expectTypeOf(withWrappedQueries).toEqualTypeOf<
681 Array<CreateQueryResult<number, Error>>
682 >()
683 })
684})