Open History to see the last commit
1import {
2 DestroyRef,
3 NgZone,
4 PendingTasks,
5 computed,
6 effect,
7 inject,
8 linkedSignal,
9 untracked,
10} from '@angular/core'
11import {
12 QueryClient,
13 notifyManager,
14 shouldThrowError,
15} from '@tanstack/query-core'
16import { signalProxy } from './signal-proxy'
17import { injectIsRestoring } from './inject-is-restoring'
18import type { MethodKeys } from './signal-proxy'
19import type {
20 DefaultedQueryObserverOptions,
21 QueryKey,
22 QueryObserver,
23 QueryObserverResult,
24} from '@tanstack/query-core'
25import type { CreateBaseQueryOptions } from './types'
26β
27/**
28 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
29 * @param optionsFn
30 * @param Observer
31 * @param excludeFunctions
32 */
33export function createBaseQuery<
34 TQueryFnData,
35 TError,
36 TData,
37 TQueryData,
38 TQueryKey extends QueryKey,
39>(
40 optionsFn: () => CreateBaseQueryOptions<
41 TQueryFnData,
42 TError,
43 TData,
44 TQueryData,
45 TQueryKey
46 >,
47 Observer: typeof QueryObserver,
48 excludeFunctions: ReadonlyArray<string>,
49) {
50 const ngZone = inject(NgZone)
51 const pendingTasks = inject(PendingTasks)
52 const queryClient = inject(QueryClient)
53 const isRestoring = injectIsRestoring()
54 const destroyRef = inject(DestroyRef)
55β
56 let destroyed = false
57 let taskCleanupRef: (() => void) | null = null
58β
59 const startPendingTask = () => {
60 if (!taskCleanupRef && !destroyed) {
61 taskCleanupRef = pendingTasks.add()
62 }
63 }
64β
65 const stopPendingTask = () => {
66 if (taskCleanupRef) {
67 taskCleanupRef()
68 taskCleanupRef = null
69 }
70 }
71β
72 const shouldBlockPendingTasks = (
73 observer: QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>,
74 result: QueryObserverResult<TData, TError>,
75 ) => {
76 return (
77 observer.getCurrentQuery().state.fetchStatus !== 'idle' ||
78 (result.fetchStatus !== 'idle' && result.isEnabled)
79 )
80 }
81β
82 /**
83 * Signal that has the default options from query client applied
84 * computed() is used so signals can be inserted into the options
85 * making it reactive. Wrapping options in a function ensures embedded expressions
86 * are preserved and can keep being applied after signal changes
87 */
88 const defaultedOptionsSignal = computed(() => {
89 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
90 defaultedOptions._optimisticResults = isRestoring()
91 ? 'isRestoring'
92 : 'optimistic'
93 return defaultedOptions
94 })
95β
96 // Computed without deps to lazy initialize the observer
97 const observerSignal = computed(() => {
98 return new Observer(queryClient, untracked(defaultedOptionsSignal))
99 })
100β
101 effect(() => {
102 observerSignal().setOptions(defaultedOptionsSignal())
103 })
104β
105 const trackObserverResult = (
106 result: QueryObserverResult<TData, TError>,
107 notifyOnChangeProps?: DefaultedQueryObserverOptions<
108 TQueryFnData,
109 TError,
110 TData,
111 TQueryData,
112 TQueryKey
113 >['notifyOnChangeProps'],
114 ) => {
115 const observer = untracked(observerSignal)
116 const trackedResult = observer.trackResult(result)
117β
118 if (!notifyOnChangeProps) {
119 autoTrackResultProperties(trackedResult)
120 }
121β
122 return trackedResult
123 }
124β
125 const autoTrackResultProperties = (
126 result: QueryObserverResult<TData, TError>,
127 ) => {
128 for (const key of Object.keys(result) as Array<
129 keyof QueryObserverResult<TData, TError>
130 >) {
131 if (key === 'promise') continue
132 const value = result[key]
133 if (typeof value === 'function') continue
134 // Access value once so QueryObserver knows this prop is tracked.
135 void value
136 }
137 }
138β
139 const subscribeToObserver = () => {
140 const observer = untracked(observerSignal)
141 const initialState = observer.getCurrentResult()
142 if (shouldBlockPendingTasks(observer, initialState)) {
143 startPendingTask()
144 }
145β
146 return observer.subscribe((state) => {
147 if (shouldBlockPendingTasks(observer, state)) {
148 startPendingTask()
149 } else {
150 stopPendingTask()
151 }
152β
153 queueMicrotask(() => {
154 if (destroyed) return
155 notifyManager.batch(() => {
156 ngZone.run(() => {
157 if (
158 state.isError &&
159 !state.isFetching &&
160 shouldThrowError(observer.options.throwOnError, [
161 state.error,
162 observer.getCurrentQuery(),
163 ])
164 ) {
165 ngZone.onError.emit(state.error)
166 throw state.error
167 }
168 const trackedState = trackObserverResult(
169 state,
170 observer.options.notifyOnChangeProps,
171 )
172 resultSignal.set(trackedState)
173 })
174 })
175 })
176 })
177 }
178β
179 const resultSignal = linkedSignal({
180 source: defaultedOptionsSignal,
181 computation: () => {
182 const observer = untracked(observerSignal)
183 const defaultedOptions = defaultedOptionsSignal()
184β
185 const result = observer.getOptimisticResult(defaultedOptions)
186 return trackObserverResult(result, defaultedOptions.notifyOnChangeProps)
187 },
188 })
189β
190 effect((onCleanup) => {
191 if (isRestoring()) {
192 return
193 }
194 const unsubscribe = untracked(() =>
195 ngZone.runOutsideAngular(() => subscribeToObserver()),
196 )
197 onCleanup(() => {
198 unsubscribe()
199 stopPendingTask()
200 })
201 })
202β
203 destroyRef.onDestroy(() => {
204 destroyed = true
205 stopPendingTask()
206 })
207β
208 return signalProxy(
209 resultSignal.asReadonly(),
210 excludeFunctions as Array<MethodKeys<QueryObserverResult<TData, TError>>>,
211 )
212}