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