Open History to see the last commit
1import {
2 NgZone,
3 VERSION,
4 computed,
5 effect,
6 inject,
7 signal,
8 untracked,
9} from '@angular/core'
10import {
11 QueryClient,
12 notifyManager,
13 shouldThrowError,
14} from '@tanstack/query-core'
15import { signalProxy } from './signal-proxy'
16import { injectIsRestoring } from './inject-is-restoring'
17import { PENDING_TASKS } from './pending-tasks-compat'
18import type { PendingTaskRef } from './pending-tasks-compat'
19import type {
20 QueryKey,
21 QueryObserver,
22 QueryObserverResult,
23} from '@tanstack/query-core'
24import type { CreateBaseQueryOptions } from './types'
25β
26/**
27 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
28 * @param optionsFn - A function that returns the query options. It is re-run when the signals it
29 * reads change.
30 * @param Observer - The observer class from query-core (`QueryObserver` or `InfiniteQueryObserver`).
31 * @returns The query result, with each value field exposed as a computed signal. Functions such as
32 * `refetch` stay callable functions.
33 */
34export function createBaseQuery<
35 TQueryFnData,
36 TError,
37 TData,
38 TQueryData,
39 TQueryKey extends QueryKey,
40>(
41 optionsFn: () => CreateBaseQueryOptions<
42 TQueryFnData,
43 TError,
44 TData,
45 TQueryData,
46 TQueryKey
47 >,
48 Observer: typeof QueryObserver,
49) {
50 const ngZone = inject(NgZone)
51 const pendingTasks = inject(PENDING_TASKS)
52 const queryClient = inject(QueryClient)
53 const isRestoring = injectIsRestoring()
54β
55 /**
56 * Signal that has the default options from query client applied
57 * computed() is used so signals can be inserted into the options
58 * making it reactive. Wrapping options in a function ensures embedded expressions
59 * are preserved and can keep being applied after signal changes
60 */
61 const defaultedOptionsSignal = computed(() => {
62 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
63 defaultedOptions._optimisticResults = isRestoring()
64 ? 'isRestoring'
65 : 'optimistic'
66 return defaultedOptions
67 })
68β
69 const observerSignal = (() => {
70 let instance: QueryObserver<
71 TQueryFnData,
72 TError,
73 TData,
74 TQueryData,
75 TQueryKey
76 > | null = null
77β
78 return computed(() => {
79 return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
80 })
81 })()
82β
83 const optimisticResultSignal = computed(() =>
84 observerSignal().getOptimisticResult(defaultedOptionsSignal()),
85 )
86β
87 const resultFromSubscriberSignal = signal<QueryObserverResult<
88 TData,
89 TError
90 > | null>(null)
91β
92 effect(
93 (onCleanup) => {
94 const observer = observerSignal()
95 const defaultedOptions = defaultedOptionsSignal()
96β
97 untracked(() => {
98 observer.setOptions(defaultedOptions)
99 })
100 onCleanup(() => {
101 ngZone.run(() => resultFromSubscriberSignal.set(null))
102 })
103 },
104 {
105 // Set allowSignalWrites to support Angular < v19
106 // Set to undefined to avoid warning on newer versions
107 allowSignalWrites: VERSION.major < '19' || undefined,
108 },
109 )
110β
111 effect((onCleanup) => {
112 // observer.trackResult is not used as this optimization is not needed for Angular
113 const observer = observerSignal()
114 let pendingTaskRef: PendingTaskRef | null = null
115β
116 const unsubscribe = isRestoring()
117 ? () => undefined
118 : untracked(() =>
119 ngZone.runOutsideAngular(() => {
120 return observer.subscribe(
121 notifyManager.batchCalls((state) => {
122 ngZone.run(() => {
123 if (state.fetchStatus === 'fetching' && !pendingTaskRef) {
124 pendingTaskRef = pendingTasks.add()
125 }
126β
127 if (state.fetchStatus === 'idle' && pendingTaskRef) {
128 pendingTaskRef()
129 pendingTaskRef = null
130 }
131β
132 if (
133 state.isError &&
134 !state.isFetching &&
135 shouldThrowError(observer.options.throwOnError, [
136 state.error,
137 observer.getCurrentQuery(),
138 ])
139 ) {
140 ngZone.onError.emit(state.error)
141 throw state.error
142 }
143 resultFromSubscriberSignal.set(state)
144 })
145 }),
146 )
147 }),
148 )
149β
150 onCleanup(() => {
151 if (pendingTaskRef) {
152 pendingTaskRef()
153 pendingTaskRef = null
154 }
155 unsubscribe()
156 })
157 })
158β
159 return signalProxy(
160 computed(() => {
161 const subscriberResult = resultFromSubscriberSignal()
162 const optimisticResult = optimisticResultSignal()
163 const result = subscriberResult ?? optimisticResult
164β
165 // Wrap methods to ensure observer has latest options before execution
166 const observer = observerSignal()
167β
168 const originalRefetch = result.refetch
169 return {
170 ...result,
171 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion -- keeps the declared 'refetch' type, which the wrapper would widen to 'RefetchOptions | undefined'
172 refetch: ((...args: Parameters<typeof originalRefetch>) => {
173 observer.setOptions(defaultedOptionsSignal())
174 return originalRefetch(...args)
175 }) as typeof originalRefetch,
176 }
177 }),
178 )
179}