Open History to see the last commit
1import {
2 DestroyRef,
3 Injector,
4 computed,
5 effect,
6 inject,
7 runInInjectionContext,
8 signal,
9 untracked,
10} from '@angular/core'
11import { notifyManager } from '@tanstack/query-core'
12import { signalProxy } from './signal-proxy'
13import { lazyInit } from './lazy-init'
14import type { QueryClient, QueryKey, QueryObserver } from '@tanstack/query-core'
15import type { CreateBaseQueryOptions, CreateBaseQueryResult } from './types'
16β
17/**
18 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
19 */
20export function createBaseQuery<
21 TQueryFnData,
22 TError,
23 TData,
24 TQueryData,
25 TQueryKey extends QueryKey,
26>(
27 options: (
28 client: QueryClient,
29 ) => CreateBaseQueryOptions<
30 TQueryFnData,
31 TError,
32 TData,
33 TQueryData,
34 TQueryKey
35 >,
36 Observer: typeof QueryObserver,
37 queryClient: QueryClient,
38): CreateBaseQueryResult<TData, TError> {
39 const injector = inject(Injector)
40β
41 return lazyInit(() => {
42 return runInInjectionContext(injector, () => {
43 const destroyRef = inject(DestroyRef)
44 /**
45 * Signal that has the default options from query client applied
46 * computed() is used so signals can be inserted into the options
47 * making it reactive. Wrapping options in a function ensures embedded expressions
48 * are preserved and can keep being applied after signal changes
49 */
50 const defaultedOptionsSignal = computed(() => {
51 const defaultedOptions = queryClient.defaultQueryOptions(
52 options(queryClient),
53 )
54 defaultedOptions._optimisticResults = 'optimistic'
55 return defaultedOptions
56 })
57β
58 const observer = new Observer<
59 TQueryFnData,
60 TError,
61 TData,
62 TQueryData,
63 TQueryKey
64 >(queryClient, defaultedOptionsSignal())
65β
66 const resultSignal = signal(
67 observer.getOptimisticResult(defaultedOptionsSignal()),
68 )
69β
70 // Effects should not be called inside reactive contexts
71 untracked(() =>
72 effect(() => {
73 const defaultedOptions = defaultedOptionsSignal()
74 observer.setOptions(defaultedOptions, {
75 // Do not notify on updates because of changes in the options because
76 // these changes should already be reflected in the optimistic result.
77 listeners: false,
78 })
79 untracked(() => {
80 resultSignal.set(observer.getOptimisticResult(defaultedOptions))
81 })
82 }),
83 )
84β
85 // observer.trackResult is not used as this optimization is not needed for Angular
86 const unsubscribe = observer.subscribe(
87 notifyManager.batchCalls((val) => resultSignal.set(val)),
88 )
89 destroyRef.onDestroy(unsubscribe)
90β
91 return signalProxy(resultSignal) as CreateBaseQueryResult<TData, TError>
92 })
93 })
94}