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

create-base-query.ts

175 lines4.7 KB

1import {
2 NgZone,
3 VERSION,
4 computed,
5 effect,
6 inject,
7 signal,
8 untracked,
9} from '@angular/core'
10import {
11 QueryClient,
12 notifyManager,
13 shouldThrowError,
14} from '@tanstack/query-core'
15import { signalProxy } from './signal-proxy'
16import { injectIsRestoring } from './inject-is-restoring'
17import { PENDING_TASKS } from './pending-tasks-compat'
18import type { PendingTaskRef } from './pending-tasks-compat'
19import type {
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(PENDING_TASKS)
49 const queryClient = inject(QueryClient)
50 const isRestoring = injectIsRestoring()
51​
52 /**
53 * Signal that has the default options from query client applied
54 * computed() is used so signals can be inserted into the options
55 * making it reactive. Wrapping options in a function ensures embedded expressions
56 * are preserved and can keep being applied after signal changes
57 */
58 const defaultedOptionsSignal = computed(() => {
59 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
60 defaultedOptions._optimisticResults = isRestoring()
61 ? 'isRestoring'
62 : 'optimistic'
63 return defaultedOptions
64 })
65​
66 const observerSignal = (() => {
67 let instance: QueryObserver<
68 TQueryFnData,
69 TError,
70 TData,
71 TQueryData,
72 TQueryKey
73 > | null = null
74​
75 return computed(() => {
76 return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
77 })
78 })()
79​
80 const optimisticResultSignal = computed(() =>
81 observerSignal().getOptimisticResult(defaultedOptionsSignal()),
82 )
83​
84 const resultFromSubscriberSignal = signal<QueryObserverResult<
85 TData,
86 TError
87 > | null>(null)
88​
89 effect(
90 (onCleanup) => {
91 const observer = observerSignal()
92 const defaultedOptions = defaultedOptionsSignal()
93​
94 untracked(() => {
95 observer.setOptions(defaultedOptions)
96 })
97 onCleanup(() => {
98 ngZone.run(() => resultFromSubscriberSignal.set(null))
99 })
100 },
101 {
102 // Set allowSignalWrites to support Angular < v19
103 // Set to undefined to avoid warning on newer versions
104 allowSignalWrites: VERSION.major < '19' || undefined,
105 },
106 )
107​
108 effect((onCleanup) => {
109 // observer.trackResult is not used as this optimization is not needed for Angular
110 const observer = observerSignal()
111 let pendingTaskRef: PendingTaskRef | null = null
112​
113 const unsubscribe = isRestoring()
114 ? () => undefined
115 : untracked(() =>
116 ngZone.runOutsideAngular(() => {
117 return observer.subscribe(
118 notifyManager.batchCalls((state) => {
119 ngZone.run(() => {
120 if (state.fetchStatus === 'fetching' && !pendingTaskRef) {
121 pendingTaskRef = pendingTasks.add()
122 }
123​
124 if (state.fetchStatus === 'idle' && pendingTaskRef) {
125 pendingTaskRef()
126 pendingTaskRef = null
127 }
128​
129 if (
130 state.isError &&
131 !state.isFetching &&
132 shouldThrowError(observer.options.throwOnError, [
133 state.error,
134 observer.getCurrentQuery(),
135 ])
136 ) {
137 ngZone.onError.emit(state.error)
138 throw state.error
139 }
140 resultFromSubscriberSignal.set(state)
141 })
142 }),
143 )
144 }),
145 )
146​
147 onCleanup(() => {
148 if (pendingTaskRef) {
149 pendingTaskRef()
150 pendingTaskRef = null
151 }
152 unsubscribe()
153 })
154 })
155​
156 return signalProxy(
157 computed(() => {
158 const subscriberResult = resultFromSubscriberSignal()
159 const optimisticResult = optimisticResultSignal()
160 const result = subscriberResult ?? optimisticResult
161​
162 // Wrap methods to ensure observer has latest options before execution
163 const observer = observerSignal()
164​
165 const originalRefetch = result.refetch
166 return {
167 ...result,
168 refetch: ((...args: Parameters<typeof originalRefetch>) => {
169 observer.setOptions(defaultedOptionsSignal())
170 return originalRefetch(...args)
171 }) as typeof originalRefetch,
172 }
173 }),
174 )