Open History to see the last commit
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>
49}
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
96}
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 tuple element so every entry's
143 * `queryFn`/`select`/`throwOnError` are inferred individually, up to 20 elements β past that, tuple
144 * recursion falls back to a single homogeneous options type. An opaque array (e.g. `unknown[]`) is returned
145 * as-is; a non-tuple array of a known element type is mapped to that element type instead, with no such
146 * limit.
147 * @template T - The type of the `queries` array as written at the call site.
148 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
149 * be set explicitly.
150 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
151 * meant to be set explicitly.
152 */
153export type QueriesOptions<
154 T extends Array<any>,
155 TResults extends Array<any> = [],
156 TDepth extends ReadonlyArray<number> = [],
157> = TDepth['length'] extends MAXIMUM_DEPTH
158 ? Array<QueryObserverOptionsForCreateQueries>
159 : T extends []
160 ? []
161 : T extends [infer Head]
162 ? [...TResults, GetCreateQueryOptionsForCreateQueries<Head>]
163 : T extends [infer Head, ...infer Tails]
164 ? QueriesOptions<
165 [...Tails],
166 [...TResults, GetCreateQueryOptionsForCreateQueries<Head>],
167 [...TDepth, 1]
168 >
169 : ReadonlyArray<unknown> extends T
170 ? T
171 : // If T is *some* array but we couldn't assign unknown[] to it, then it must hold some known/homogeneous type!
172 // use this to infer the param types in the case of Array.map() argument
173 T extends Array<
174 QueryObserverOptionsForCreateQueries<
175 infer TQueryFnData,
176 infer TError,
177 infer TData,
178 infer TQueryKey
179 >
180 >
181 ? Array<
182 QueryObserverOptionsForCreateQueries<
183 TQueryFnData,
184 TError,
185 TData,
186 TQueryKey
187 >
188 >
189 : // Fallback
190 Array<QueryObserverOptionsForCreateQueries>
191β
192/**
193 * The result type returned by `injectQueries`, when no `combine` is provided. Mirrors {@link QueriesOptions}:
194 * each tuple element's result type is inferred individually, up to 20 elements β past that, tuple recursion
195 * falls back to a single homogeneous {@link CreateQueryResult} type. A non-tuple array is mapped per-element
196 * instead, with no such limit β every entry keeps its individually inferred type regardless of array length.
197 * @template T - The type of the `queries` array, as inferred by {@link QueriesOptions}.
198 * @template TResults - The internal accumulator that this type builds during recursion. It is not meant to
199 * be set explicitly.
200 * @template TDepth - The internal recursion-depth counter, checked against the 20-element limit. It is not
201 * meant to be set explicitly.
202 */
203export type QueriesResults<
204 T extends Array<any>,
205 TResults extends Array<any> = [],
206 TDepth extends ReadonlyArray<number> = [],
207> = TDepth['length'] extends MAXIMUM_DEPTH
208 ? Array<CreateQueryResult>
209 : T extends []
210 ? []
211 : T extends [infer Head]
212 ? [...TResults, GetCreateQueryResult<Head>]
213 : T extends [infer Head, ...infer Tails]
214 ? QueriesResults<
215 [...Tails],
216 [...TResults, GetCreateQueryResult<Head>],
217 [...TDepth, 1]
218 >
219 : { [K in keyof T]: GetCreateQueryResult<T[K]> }
220β
221/**
222 * The options for `injectQueries`: the `queries` to run, and an optional `combine` function that
223 * derives a single result from all the query results.
224 */
225export interface InjectQueriesOptions<
226 T extends Array<any>,
227 TCombinedResult = QueriesResults<T>,
228> {
229 /**
230 * The array of query options to run, one query per element.
231 */
232 queries:
233 | readonly [...QueriesOptions<T>]
234 | readonly [
235 ...{ [K in keyof T]: GetCreateQueryOptionsForCreateQueries<T[K]> },
236 ]
237 /**
238 * Combines the results of all the queries into a single value, which `injectQueries` returns
239 * instead of the results array.
240 */
241 combine?: (result: QueriesResults<T>) => TCombinedResult
242}
243β
244/**
245 * Injects a signal to fetch a variable number of queries.
246 *
247 * The `queries` key accepts an array with query option objects mostly identical to `injectQuery`'s. Having
248 * the same query key more than once in the array of query objects may cause some data to be shared between
249 * queries. To avoid this, consider de-duplicating the queries and map the results back to the desired
250 * structure.
251 *
252 * The `combine` option can be used to combine the results of the queries into a single value. The result
253 * will be structurally shared to be as referentially stable as possible.
254 * @param optionsFn - A function returning the queries' options β an array of query option objects under
255 * `queries`, and an optional `combine`. Similar to `computed` from Angular, this function runs in the
256 * reactive context, so signals read inside it (e.g. to build the `queries` array) drive the queries.
257 * @param injector - The `Injector` in which to create the queries. If this is not provided, the current
258 * injection context will be used instead (via `inject`).
259 * @returns A `Signal` with the combined result. Without `combine`, this is an array with all the query
260 * results, in the same order as the input. When `combine` is provided, this is the value returned by
261 * `combine` instead.
262 * @remarks Unlike `injectQuery`, `injectQueries` cannot infer the `data` argument of an _inline_ `select`
263 * from its sibling `queryFn`. Because `injectQueries` infers the type of the whole `queries` array at once,
264 * the `select` parameter of a query object written inline cannot be contextually typed from that same
265 * object's `queryFn`, so it falls back to `unknown` β a
266 * [known TypeScript limitation](https://github.com/TanStack/query/issues/6556). Annotate the `select`
267 * parameter explicitly, or define the query with {@link queryOptions}, which resolves its types in a single
268 * object _before_ it reaches `injectQueries`, to work around this β see the example below.
269 * @example
270 * ```angular-ts
271 * @Component({
272 * selector: 'posts',
273 * template: `
274 * <ul>
275 * @for (query of postQueries(); track $index) {
276 * @if (query.isPending()) {
277 * <li>Loading...</li>
278 * } @else if (query.isError()) {
279 * <li>Error: {{ query.error()?.message }}</li>
280 * } @else {
281 * <li>{{ query.data().title }}</li>
282 * }
283 * }
284 * </ul>
285 * `,
286 * })
287 * export class Posts {
288 * readonly ids = signal([1, 2, 3])
289 *
290 * readonly postQueries = injectQueries(() => ({
291 * queries: this.ids().map((id) => ({
292 * queryKey: ['post', id],
293 * queryFn: () => fetchPost(id),
294 * staleTime: Infinity,
295 * })),
296 * }))
297 * }
298 * ```
299 * @example
300 * Combining results into a single value:
301 * ```angular-ts
302 * @Component({
303 * selector: 'posts',
304 * template: `
305 * @if (combined().isPending) {
306 * Loading...
307 * } @else if (combined().isError) {
308 * Error loading posts
309 * } @else {
310 * <ul>
311 * @for (post of combined().data; track post?.id) {
312 * <li>{{ post?.title }}</li>
313 * }
314 * </ul>
315 * }
316 * `,
317 * })
318 * export class Posts {
319 * readonly ids = signal([1, 2, 3])
320 *
321 * readonly combined = injectQueries(() => ({
322 * queries: this.ids().map((id) => ({
323 * queryKey: ['post', id],
324 * queryFn: () => fetchPost(id),
325 * })),
326 * combine: (postQueries) => ({
327 * data: postQueries.map((query) => query.data),
328 * isPending: postQueries.some((query) => query.isPending),
329 * isError: postQueries.some((query) => query.isError),
330 * }),
331 * }))
332 * }
333 * ```
334 * @example
335 * Typing `select` via {@link queryOptions}. Note that spreading a `queryOptions` result and overriding
336 * `select` inline still falls back to `unknown` β wrap the spread in `queryOptions` again so the override is
337 * resolved before it reaches `injectQueries`:
338 * ```angular-ts
339 * const postOptions = (id: number) =>
340 * queryOptions({
341 * queryKey: ['post', id],
342 * queryFn: () => fetchPost(id),
343 * })
344 *
345 * @Component({
346 * selector: 'post-title',
347 * template: `<h1>{{ fixed()[0].data() }}</h1>`,
348 * })
349 * export class PostTitle {
350 * readonly id = signal(1)
351 *
352 * readonly broken = injectQueries(() => ({
353 * queries: [
354 * {
355 * ...postOptions(this.id()),
356 * // β `data` is `unknown` here
357 * select: (data) => data.title,
358 * },
359 * ],
360 * }))
361 *
362 * readonly fixed = injectQueries(() => ({
363 * queries: [
364 * queryOptions({
365 * ...postOptions(this.id()),
366 * // β
`data` is `Post`
367 * select: (data) => data.title,
368 * }),
369 * ],
370 * }))
371 * }
372 * ```
373 */
374export function injectQueries<
375 T extends Array<any>,
376 TCombinedResult = QueriesResults<T>,
377>(
378 optionsFn: () => InjectQueriesOptions<T, TCombinedResult>,
379 injector?: Injector,
380): Signal<TCombinedResult> {
381 !injector && assertInInjectionContext(injectQueries)
382 return runInInjectionContext(injector ?? inject(Injector), () => {
383 const destroyRef = inject(DestroyRef)
384 const ngZone = inject(NgZone)
385 const queryClient = inject(QueryClient)
386 const isRestoring = injectIsRestoring()
387β
388 /**
389 * Signal that has the default options from query client applied
390 * computed() is used so signals can be inserted into the options
391 * making it reactive. Wrapping options in a function ensures embedded expressions
392 * are preserved and can keep being applied after signal changes
393 */
394 const optionsSignal = computed(() => {
395 return optionsFn()
396 })
397β
398 const defaultedQueries = computed(() => {
399 return optionsSignal().queries.map((opts) => {
400 const defaultedOptions = queryClient.defaultQueryOptions(
401 opts as QueryObserverOptions,
402 )
403 // Make sure the results are already in fetching state before subscribing or updating options
404 defaultedOptions._optimisticResults = isRestoring()
405 ? 'isRestoring'
406 : 'optimistic'
407β
408 return defaultedOptions
409 })
410 })
411β
412 const observerSignal = (() => {
413 let instance: QueriesObserver<TCombinedResult> | null = null
414β
415 return computed(() => {
416 return (instance ||= new QueriesObserver<TCombinedResult>(
417 queryClient,
418 defaultedQueries(),
419 optionsSignal() as QueriesObserverOptions<TCombinedResult>,
420 ))
421 })
422 })()
423β
424 const optimisticResultSignal = computed(() =>
425 observerSignal().getOptimisticResult(
426 defaultedQueries(),
427 (optionsSignal() as QueriesObserverOptions<TCombinedResult>).combine,
428 ),
429 )
430β
431 // Do not notify on updates because of changes in the options because
432 // these changes should already be reflected in the optimistic result.
433 effect(() => {
434 observerSignal().setQueries(
435 defaultedQueries(),
436 optionsSignal() as QueriesObserverOptions<TCombinedResult>,
437 )
438 })
439β
440 const optimisticCombinedResultSignal = computed(() => {
441 const [_optimisticResult, getCombinedResult, trackResult] =
442 optimisticResultSignal()
443 return getCombinedResult(trackResult())
444 })
445β
446 const resultFromSubscriberSignal = signal<TCombinedResult | null>(null)
447β
448 effect(() => {
449 const observer = observerSignal()
450 const [_optimisticResult, getCombinedResult] = optimisticResultSignal()
451β
452 untracked(() => {
453 const unsubscribe = isRestoring()
454 ? () => undefined
455 : ngZone.runOutsideAngular(() =>
456 observer.subscribe(
457 notifyManager.batchCalls((state) => {
458 resultFromSubscriberSignal.set(getCombinedResult(state))
459 }),
460 ),
461 )
462β
463 destroyRef.onDestroy(unsubscribe)
464 })
465 })
466β
467 const resultSignal = computed(() => {
468 const subscriberResult = resultFromSubscriberSignal()
469 const optimisticResult = optimisticCombinedResultSignal()
470 return subscriberResult ?? optimisticResult
471 })
472β
473 return computed(() => {
474 const result = resultSignal()
475 const { combine } = optionsSignal()
476β
477 return combine
478 ? result
479 : (result as QueriesResults<T>).map((query) =>
480 signalProxy(signal(query)),
481 )
482 })
483 }) as unknown as Signal<TCombinedResult>
484}