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

inject-queries.ts

501 lines18.0 KB

1import {
2 QueriesObserver,
3 QueryClient,
4 notifyManager,
5} from '@tanstack/query-core'
6import {
7 DestroyRef,
8 Injector,
9 NgZone,
10 assertInInjectionContext,
11 computed,
12 effect,
13 inject,
14 runInInjectionContext,
15 signal,
16 untracked,
17} from '@angular/core'
18import { signalProxy } from './signal-proxy'
19import { injectIsRestoring } from './inject-is-restoring'
20import type {
21 DefaultError,
22 OmitKeyof,
23 QueriesObserverOptions,
24 QueriesPlaceholderDataFunction,
25 QueryFunction,
26 QueryKey,
27 QueryObserverOptions,
28 ThrowOnError,
29} from '@tanstack/query-core'
30import type {
31 CreateQueryOptions,
32 CreateQueryResult,
33 DefinedCreateQueryResult,
34} from './types'
35import type { Signal } from '@angular/core'
36​
37// This defines the `CreateQueryOptions` that are accepted in `QueriesOptions` & `GetOptions`.
38// `placeholderData` function always gets undefined passed
39type QueryObserverOptionsForCreateQueries<
40 TQueryFnData = unknown,
41 TError = DefaultError,
42 TData = TQueryFnData,
43 TQueryKey extends QueryKey = QueryKey,
44> = OmitKeyof<
45 CreateQueryOptions<TQueryFnData, TError, TData, TQueryKey>,
46 'placeholderData'
47> & {
48 placeholderData?: TQueryFnData | QueriesPlaceholderDataFunction<TQueryFnData>
50​
51// Avoid TS depth-limit error in case of large array literal
52type MAXIMUM_DEPTH = 20
53​
54// Widen the type of the symbol to enable type inference even if skipToken is not immutable.
55type SkipTokenForCreateQueries = symbol
56​
57type GetCreateQueryOptionsForCreateQueries<T> =
58 // Part 1: responsible for applying explicit type parameter to function arguments, if object { queryFnData: TQueryFnData, error: TError, data: TData }
59 T extends {
60 queryFnData: infer TQueryFnData
61 error?: infer TError
62 data: infer TData
63 }
64 ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>
65 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
66 ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>
67 : T extends { data: infer TData; error?: infer TError }
68 ? QueryObserverOptionsForCreateQueries<unknown, TError, TData>
69 : // Part 2: responsible for applying explicit type parameter to function arguments, if tuple [TQueryFnData, TError, TData]
70 T extends [infer TQueryFnData, infer TError, infer TData]
71 ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError, TData>
72 : T extends [infer TQueryFnData, infer TError]
73 ? QueryObserverOptionsForCreateQueries<TQueryFnData, TError>
74 : T extends [infer TQueryFnData]
75 ? QueryObserverOptionsForCreateQueries<TQueryFnData>
76 : // Part 3: responsible for inferring and enforcing type if no explicit parameter was provided
77 T extends {
78 queryFn?:
79 | QueryFunction<infer TQueryFnData, infer TQueryKey>
80 | SkipTokenForCreateQueries
81 select?: (data: any) => infer TData
82 throwOnError?: ThrowOnError<any, infer TError, any, any>
83 }
84 ? QueryObserverOptionsForCreateQueries<
85 TQueryFnData,
86 unknown extends TError ? DefaultError : TError,
87 unknown extends TData ? TQueryFnData : TData,
88 TQueryKey
89 >
90 : // Fallback
91 QueryObserverOptionsForCreateQueries
92​
93// A defined initialData setting should return a DefinedCreateQueryResult rather than CreateQueryResult
94type GetDefinedOrUndefinedQueryResult<T, TData, TError = unknown> = T extends {
95 initialData?: infer TInitialData
97 ? unknown extends TInitialData
98 ? CreateQueryResult<TData, TError>
99 : TInitialData extends TData
100 ? DefinedCreateQueryResult<TData, TError>
101 : TInitialData extends () => infer TInitialDataResult
102 ? unknown extends TInitialDataResult
103 ? CreateQueryResult<TData, TError>
104 : TInitialDataResult extends TData
105 ? DefinedCreateQueryResult<TData, TError>
106 : CreateQueryResult<TData, TError>
107 : CreateQueryResult<TData, TError>
108 : CreateQueryResult<TData, TError>
109​
110type GetCreateQueryResult<T> =
111 // Part 1: responsible for mapping explicit type parameter to function result, if object
112 T extends { queryFnData: any; error?: infer TError; data: infer TData }
113 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
114 : T extends { queryFnData: infer TQueryFnData; error?: infer TError }
115 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
116 : T extends { data: infer TData; error?: infer TError }
117 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
118 : // Part 2: responsible for mapping explicit type parameter to function result, if tuple
119 T extends [any, infer TError, infer TData]
120 ? GetDefinedOrUndefinedQueryResult<T, TData, TError>
121 : T extends [infer TQueryFnData, infer TError]
122 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData, TError>
123 : T extends [infer TQueryFnData]
124 ? GetDefinedOrUndefinedQueryResult<T, TQueryFnData>
125 : // Part 3: responsible for mapping inferred type to results, if no explicit parameter was provided
126 T extends {
127 queryFn?:
128 | QueryFunction<infer TQueryFnData, any>
129 | SkipTokenForCreateQueries
130 select?: (data: any) => infer TData
131 throwOnError?: ThrowOnError<any, infer TError, any, any>
132 }
133 ? GetDefinedOrUndefinedQueryResult<
134 T,
135 unknown extends TData ? TQueryFnData : TData,
136 unknown extends TError ? DefaultError : TError
137 >
138 : // Fallback
139 CreateQueryResult
140​
141/**
142 * The `queries` array accepted by `injectQueries`. Recursively unwraps each
143 * tuple element so every entry's `queryFn`/`select`/`throwOnError` are inferred
144 * individually, up to 20 elements β€” past that, tuple recursion falls back to a
145 * single homogeneous options type. An opaque array (e.g. `unknown[]`) is
146 * returned as-is; a non-tuple array of a known element type is mapped to that
147 * element type instead, with no such limit.
148 *
149 * @template T - The type of the `queries` array as written at the call site.
150 * @template TResults - The internal accumulator that this type builds during
151 * recursion. It is not meant to be set explicitly.
152 * @template TDepth - The internal recursion-depth counter, checked against the
153 * 20-element limit. It is not meant to be set explicitly.
154 */
155export type QueriesOptions<
156 T extends Array<any>,
157 TResults extends Array<any> = [],
158 TDepth extends ReadonlyArray<number> = [],
159> = TDepth['length'] extends MAXIMUM_DEPTH
160 ? Array<QueryObserverOptionsForCreateQueries>
161 : T extends []
162 ? []
163 : T extends [infer Head]
164 ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>]
165 : T extends [infer Head, ...infer Tails]
166 ? QueriesOptions<
167 [...Tails],
168 [...TResults, GetCreateQueryOptionsForCreateQueries<Head>],
169 [...TDepth, 1]
170 >
171 : ReadonlyArray<unknown> extends T
172 ? T
173 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
174 // use this to infer the param types in the case of Array.map() argument
175 T extends Array<
176 QueryObserverOptionsForCreateQueries<
177 infer TQueryFnData,
178 infer TError,
179 infer TData,
180 infer TQueryKey
181 >
182 >
183 ? Array<
184 QueryObserverOptionsForCreateQueries<
185 TQueryFnData,
186 TError,
187 TData,
188 TQueryKey
189 >
190 >
191 : // Fallback
192 Array<QueryObserverOptionsForCreateQueries>
193​
194/**
195 * The result type returned by `injectQueries`, when no `combine` is provided.
196 * Mirrors {@link QueriesOptions}: each tuple element's result type is inferred
197 * individually, up to 20 elements β€” past that, tuple recursion falls back to a
198 * single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped
199 * per-element instead, with no such limit β€” every entry keeps its individually
200 * inferred type regardless of array length.
201 *
202 * @template T - The type of the `queries` array, as inferred by
203 * {@link QueriesOptions}.
204 * @template TResults - The internal accumulator that this type builds during
205 * recursion. It is not meant to be set explicitly.
206 * @template TDepth - The internal recursion-depth counter, checked against the
207 * 20-element limit. It is not meant to be set explicitly.
208 */
209export type QueriesResults<
210 T extends Array<any>,
211 TResults extends Array<any> = [],
212 TDepth extends ReadonlyArray<number> = [],
213> = TDepth['length'] extends MAXIMUM_DEPTH
214 ? Array<CreateQueryResult>
215 : T extends []
216 ? []
217 : T extends [infer Head]
218 ? [...TResults, GetCreateQueryResult<Head>]
219 : T extends [infer Head, ...infer Tails]
220 ? QueriesResults<
221 [...Tails],
222 [...TResults, GetCreateQueryResult<Head>],
223 [...TDepth, 1]
224 >
225 : { [K in keyof T]: GetCreateQueryResult<T[K]> }
226​
227/**
228 * The options for `injectQueries`: the `queries` to run, and an optional
229 * `combine` function that derives a single result from all the query results.
230 */
231export interface InjectQueriesOptions<
232 T extends Array<any>,
233 TCombinedResult = QueriesResults<T>,
234> {
235 /** The array of query options to run, one query per element. */
236 queries:
237 | readonly [...QueriesOptions<T>]
238 | readonly [
239 ...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },
240 ]
241 /**
242 * Combines the results of all the queries into a single value, which
243 * `injectQueries` returns instead of the results array.
244 */
245 combine?: (result: QueriesResults<T>) => TCombinedResult
247​
248/**
249 * Injects a signal to fetch a variable number of queries.
250 *
251 * The `queries` key accepts an array with query option objects mostly identical
252 * to `injectQuery`'s. Having the same query key more than once in the array of
253 * query objects may cause some data to be shared between queries. To avoid
254 * this, consider de-duplicating the queries and map the results back to the
255 * desired structure.
256 *
257 * The `combine` option can be used to combine the results of the queries into a
258 * single value. The result will be structurally shared to be as referentially
259 * stable as possible.
260 *
261 * @remarks
262 * Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of
263 * an _inline_ `select` from its sibling `queryFn`. Because `injectQueries`
264 * infers the type of the whole `queries` array at once, the `select`
265 * parameter of a query object written inline cannot be contextually typed
266 * from that same object's `queryFn`, so it falls back to `unknown` β€” a [known
267 * TypeScript limitation](https://github.com/TanStack/query/issues/6556).
268 * Annotate the `select` parameter explicitly, or define the query with
269 * {@link queryOptions}, which resolves its types in a single object _before_
270 * it reaches `injectQueries`, to work around this β€” see the example below.
271 * @example
272 * ```angular-ts
273 * @Component({
274 * selector: 'posts',
275 * template: `
276 * <ul>
277 * @for (query of postQueries(); track $index) {
278 * @if (query.isPending()) {
279 * <li>Loading...</li>
280 * } @else if (query.isError()) {
281 * <li>Error: {{ query.error()?.message }}</li>
282 * } @else {
283 * <li>{{ query.data().title }}</li>
284 * }
285 * }
286 * </ul>
287 * `,
288 * })
289 * export class Posts {
290 * readonly ids = signal([1, 2, 3])
291 *
292 * readonly postQueries = injectQueries(() => ({
293 * queries: this.ids().map((id) => ({
294 * queryKey: ['post', id],
295 * queryFn: () => fetchPost(id),
296 * staleTime: Infinity,
297 * })),
298 * }))
299 * }
300 * ```
301 *
302 * @example
303 * Combining results into a single value:
304 * ```angular-ts
305 * @Component({
306 * selector: 'posts',
307 * template: `
308 * @if (combined().isPending) {
309 * Loading...
310 * } @else if (combined().isError) {
311 * Error loading posts
312 * } @else {
313 * <ul>
314 * @for (post of combined().data; track post?.id) {
315 * <li>{{ post?.title }}</li>
316 * }
317 * </ul>
318 * }
319 * `,
320 * })
321 * export class Posts {
322 * readonly ids = signal([1, 2, 3])
323 *
324 * readonly combined = injectQueries(() => ({
325 * queries: this.ids().map((id) => ({
326 * queryKey: ['post', id],
327 * queryFn: () => fetchPost(id),
328 * })),
329 * combine: (postQueries) => ({
330 * data: postQueries.map((query) => query.data),
331 * isPending: postQueries.some((query) => query.isPending),
332 * isError: postQueries.some((query) => query.isError),
333 * }),
334 * }))
335 * }
336 * ```
337 *
338 * @example
339 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
340 * `select` inline still falls back to `unknown` β€” wrap the spread in `queryOptions` again so the override is
341 * resolved before it reaches `injectQueries`:
342 * ```angular-ts
343 * const postOptions = (id: number) =>
344 * queryOptions({
345 * queryKey: ['post', id],
346 * queryFn: () => fetchPost(id),
347 * })
348 *
349 * @Component({
350 * selector: 'post-title',
351 * template: `<h1>{{ fixed()[0].data() }}</h1>`,
352 * })
353 * export class PostTitle {
354 * readonly id = signal(1)
355 *
356 * readonly broken = injectQueries(() => ({
357 * queries: [
358 * {
359 * ...postOptions(this.id()),
360 * // ❌ `data` is `unknown` here
361 * select: (data) => data.title,
362 * },
363 * ],
364 * }))
365 *
366 * readonly fixed = injectQueries(() => ({
367 * queries: [
368 * queryOptions({
369 * ...postOptions(this.id()),
370 * // βœ… `data` is `Post`
371 * select: (data) => data.title,
372 * }),
373 * ],
374 * }))
375 * }
376 * ```
377 *
378 * @param optionsFn - A function returning the queries' options β€” an array of
379 * query option objects under `queries`, and an optional `combine`. Similar to
380 * `computed` from Angular, this function runs in the reactive context, so
381 * signals read inside it (e.g. to build the `queries` array) drive the
382 * queries.
383 * @param injector - The `Injector` in which to create the queries. If this is
384 * not provided, the current injection context will be used instead (via
385 * `inject`).
386 * @returns A `Signal` with the combined result. Without `combine`, this is an
387 * array with all the query results, in the same order as the input. When
388 * `combine` is provided, this is the value returned by `combine` instead.
389 */
390export function injectQueries<
391 T extends Array<any>,
392 TCombinedResult = QueriesResults<T>,
393>(
394 optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,
395 injector?: Injector,
396): Signal<TCombinedResult> {
397 !injector && assertInInjectionContext(injectQueries)
398 return runInInjectionContext(injector ?? inject(Injector), () => {
399 const destroyRef = inject(DestroyRef)
400 const ngZone = inject(NgZone)
401 const queryClient = inject(QueryClient)
402 const isRestoring = injectIsRestoring()
403​
404 /**
405 * Signal that has the default options from query client applied computed()
406 * is used so signals can be inserted into the options making it reactive.
407 * Wrapping options in a function ensures embedded expressions are preserved
408 * and can keep being applied after signal changes
409 */
410 const optionsSignal = computed(() => {
411 return optionsFn()
412 })
413​
414 const defaultedQueries = computed(() => {
415 return optionsSignal().queries.map((opts) => {
416 const defaultedOptions = queryClient.defaultQueryOptions(
417 opts as QueryObserverOptions,
418 )
419 // Make sure the results are already in fetching state before subscribing or updating options
420 defaultedOptions._optimisticResults = isRestoring()
421 ? 'isRestoring'
422 : 'optimistic'
423​
424 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
425 return defaultedOptions as QueryObserverOptions
426 })
427 })
428​
429 const observerSignal = (() => {
430 let instance: QueriesObserver<TCombinedResult> | null = null
431​
432 return computed(() => {
433 return (instance ||= new QueriesObserver<TCombinedResult>(
434 queryClient,
435 defaultedQueries(),
436 optionsSignal() as QueriesObserverOptions<TCombinedResult>,
437 ))
438 })
439 })()
440​
441 const optimisticResultSignal = computed(() =>
442 observerSignal().getOptimisticResult(
443 defaultedQueries(),
444 (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,
445 ),
446 )
447​
448 // Do not notify on updates because of changes in the options because
449 // these changes should already be reflected in the optimistic result.
450 effect(() => {
451 observerSignal().setQueries(
452 defaultedQueries(),
453 optionsSignal() as QueriesObserverOptions<TCombinedResult>,
454 )
455 })
456​
457 const optimisticCombinedResultSignal = computed(() => {
458 const [_optimisticResult, getCombinedResult, trackResult] =
459 optimisticResultSignal()
460 return getCombinedResult(trackResult())
461 })
462​
463 const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)
464​
465 effect(() => {
466 const observer = observerSignal()
467 const [_optimisticResult, getCombinedResult] = optimisticResultSignal()
468​
469 untracked(() => {
470 const unsubscribe = isRestoring()
471 ? () => undefined
472 : ngZone.runOutsideAngular(() =>
473 observer.subscribe(
474 notifyManager.batchCalls((state) => {
475 resultFromSubscriberSignal.set(getCombinedResult(state))
476 }),
477 ),
478 )
479​
480 destroyRef.onDestroy(unsubscribe)
481 })
482 })
483​
484 const resultSignal = computed(() => {
485 const subscriberResult = resultFromSubscriberSignal()
486 const optimisticResult = optimisticCombinedResultSignal()
487 return subscriberResult ?? optimisticResult
488 })
489​
490 return computed(() => {
491 const result = resultSignal()
492 const { combine } = optionsSignal()
493​
494 return combine
495 ? result
496 : (result as QueriesResults<T>).map((query) =>
497 signalProxy(signal(query)),
498 )
499 })
500 }) as unknown as Signal<TCombinedResult>