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 /**
73 * Signal that has the default options from query client applied
74 * computed() is used so signals can be inserted into the options
75 * making it reactive. Wrapping options in a function ensures embedded expressions
76 * are preserved and can keep being applied after signal changes
77 */
78 const defaultedOptionsSignal = computed(() => {
79 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
80 defaultedOptions._optimisticResults = isRestoring()
81 ? 'isRestoring'
82 : 'optimistic'
83 return defaultedOptions
84 })
85β
86 // Computed without deps to lazy initialize the observer
87 const observerSignal = computed(() => {
88 return new Observer(queryClient, untracked(defaultedOptionsSignal))
89 })
90β
91 effect(() => {
92 observerSignal().setOptions(defaultedOptionsSignal())
93 })
94β
95 const trackObserverResult = (
96 result: QueryObserverResult<TData, TError>,
97 notifyOnChangeProps?: DefaultedQueryObserverOptions<
98 TQueryFnData,
99 TError,
100 TData,
101 TQueryData,
102 TQueryKey
103 >['notifyOnChangeProps'],
104 ) => {
105 const observer = untracked(observerSignal)
106 const trackedResult = observer.trackResult(result)
107β
108 if (!notifyOnChangeProps) {
109 autoTrackResultProperties(trackedResult)
110 }
111β
112 return trackedResult
113 }
114β
115 const autoTrackResultProperties = (
116 result: QueryObserverResult<TData, TError>,
117 ) => {
118 for (const key of Object.keys(result) as Array<
119 keyof QueryObserverResult<TData, TError>
120 >) {
121 if (key === 'promise') continue
122 const value = result[key]
123 if (typeof value === 'function') continue
124 // Access value once so QueryObserver knows this prop is tracked.
125 void value
126 }
127 }
128β
129 const subscribeToObserver = () => {
130 const observer = untracked(observerSignal)
131 const initialState = observer.getCurrentResult()
132 if (initialState.fetchStatus !== 'idle') {
133 startPendingTask()
134 }
135β
136 return observer.subscribe((state) => {
137 if (state.fetchStatus !== 'idle') {
138 startPendingTask()
139 } else {
140 stopPendingTask()
141 }
142β
143 queueMicrotask(() => {
144 if (destroyed) return
145 notifyManager.batch(() => {
146 ngZone.run(() => {
147 if (
148 state.isError &&
149 !state.isFetching &&
150 shouldThrowError(observer.options.throwOnError, [
151 state.error,
152 observer.getCurrentQuery(),
153 ])
154 ) {
155 ngZone.onError.emit(state.error)
156 throw state.error
157 }
158 const trackedState = trackObserverResult(
159 state,
160 observer.options.notifyOnChangeProps,
161 )
162 resultSignal.set(trackedState)
163 })
164 })
165 })
166 })
167 }
168β
169 const resultSignal = linkedSignal({
170 source: defaultedOptionsSignal,
171 computation: () => {
172 const observer = untracked(observerSignal)
173 const defaultedOptions = defaultedOptionsSignal()
174β
175 const result = observer.getOptimisticResult(defaultedOptions)
176 return trackObserverResult(result, defaultedOptions.notifyOnChangeProps)
177 },
178 })
179β
180 effect((onCleanup) => {
181 if (isRestoring()) {
182 return
183 }
184 const unsubscribe = untracked(() => subscribeToObserver())
185 onCleanup(() => {
186 unsubscribe()
187 stopPendingTask()
188 })
189 })
190β
191 destroyRef.onDestroy(() => {
192 destroyed = true
193 stopPendingTask()
194 })
195β
196 return signalProxy(
197 resultSignal.asReadonly(),
198 excludeFunctions as Array<MethodKeys<QueryObserverResult<TData, TError>>>,
199 )
200}