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

create-base-query.ts

202 lines5.1 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 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(() =>
185 ngZone.runOutsideAngular(() => subscribeToObserver()),
186 )
187 onCleanup(() => {
188 unsubscribe()
189 stopPendingTask()
190 })
191 })
192​
193 destroyRef.onDestroy(() => {
194 destroyed = true
195 stopPendingTask()
196 })
197​
198 return signalProxy(
199 resultSignal.asReadonly(),
200 excludeFunctions as Array<MethodKeys<QueryObserverResult<TData, TError>>>,
201 )