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

inject-queries.ts

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