Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

create-base-query.ts

228 lines5.6 KB

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