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

create-base-query.ts

181 lines5.1 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 *
29 * @param optionsFn - A function that returns the query options. It is re-run
30 * when the signals it reads change.
31 * @param Observer - The observer class from query-core (`QueryObserver` or
32 * `InfiniteQueryObserver`).
33 * @returns The query result, with each value field exposed as a computed
34 * signal. Functions such as `refetch` stay callable functions.
35 */
36export function createBaseQuery<
37 TQueryFnData,
38 TError,
39 TData,
40 TQueryData,
41 TQueryKey extends QueryKey,
42>(
43 optionsFn: () => CreateBaseQueryOptions<
44 TQueryFnData,
45 TError,
46 TData,
47 TQueryData,
48 TQueryKey
49 >,
50 Observer: typeof QueryObserver,
51) {
52 const ngZone = inject(NgZone)
53 const pendingTasks = inject(PENDING_TASKS)
54 const queryClient = inject(QueryClient)
55 const isRestoring = injectIsRestoring()
56​
57 /**
58 * Signal that has the default options from query client applied computed() is
59 * used so signals can be inserted into the options making it reactive.
60 * Wrapping options in a function ensures embedded expressions are preserved
61 * and can keep being applied after signal changes
62 */
63 const defaultedOptionsSignal = computed(() => {
64 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
65 defaultedOptions._optimisticResults = isRestoring()
66 ? 'isRestoring'
67 : 'optimistic'
68 return defaultedOptions
69 })
70​
71 const observerSignal = (() => {
72 let instance: QueryObserver<
73 TQueryFnData,
74 TError,
75 TData,
76 TQueryData,
77 TQueryKey
78 > | null = null
79​
80 return computed(() => {
81 return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
82 })
83 })()
84​
85 const optimisticResultSignal = computed(() =>
86 observerSignal().getOptimisticResult(defaultedOptionsSignal()),
87 )
88​
89 const resultFromSubscriberSignal = signal<QueryObserverResult<
90 TData,
91 TError
92 > | null>(null)
93​
94 effect(
95 (onCleanup) => {
96 const observer = observerSignal()
97 const defaultedOptions = defaultedOptionsSignal()
98​
99 untracked(() => {
100 observer.setOptions(defaultedOptions)
101 })
102 onCleanup(() => {
103 ngZone.run(() => resultFromSubscriberSignal.set(null))
104 })
105 },
106 {
107 // Set allowSignalWrites to support Angular < v19
108 // Set to undefined to avoid warning on newer versions
109 allowSignalWrites: VERSION.major < '19' || undefined,
110 },
111 )
112​
113 effect((onCleanup) => {
114 // observer.trackResult is not used as this optimization is not needed for Angular
115 const observer = observerSignal()
116 let pendingTaskRef: PendingTaskRef | null = null
117​
118 const unsubscribe = isRestoring()
119 ? () => undefined
120 : untracked(() =>
121 ngZone.runOutsideAngular(() => {
122 return observer.subscribe(
123 notifyManager.batchCalls((state) => {
124 ngZone.run(() => {
125 if (state.fetchStatus === 'fetching' && !pendingTaskRef) {
126 pendingTaskRef = pendingTasks.add()
127 }
128​
129 if (state.fetchStatus === 'idle' && pendingTaskRef) {
130 pendingTaskRef()
131 pendingTaskRef = null
132 }
133​
134 if (
135 state.isError &&
136 !state.isFetching &&
137 shouldThrowError(observer.options.throwOnError, [
138 state.error,
139 observer.getCurrentQuery(),
140 ])
141 ) {
142 ngZone.onError.emit(state.error)
143 throw state.error
144 }
145 resultFromSubscriberSignal.set(state)
146 })
147 }),
148 )
149 }),
150 )
151​
152 onCleanup(() => {
153 if (pendingTaskRef) {
154 pendingTaskRef()
155 pendingTaskRef = null
156 }
157 unsubscribe()
158 })
159 })
160​
161 return signalProxy(
162 computed(() => {
163 const subscriberResult = resultFromSubscriberSignal()
164 const optimisticResult = optimisticResultSignal()
165 const result = subscriberResult ?? optimisticResult
166​
167 // Wrap methods to ensure observer has latest options before execution
168 const observer = observerSignal()
169​
170 const originalRefetch = result.refetch
171 return {
172 ...result,
173 // oxlint-disable-next-line typescript/no-unnecessary-type-assertion
174 refetch: ((...args: Parameters<typeof originalRefetch>) => {
175 observer.setOptions(defaultedOptionsSignal())
176 return originalRefetch(...args)
177 }) as typeof originalRefetch,
178 }
179 }),
180 )