Open History to see the last commit
1import {
2 DestroyRef,
3 NgZone,
4 VERSION,
5 computed,
6 effect,
7 inject,
8 signal,
9 untracked,
10} from '@angular/core'
11import { QueryClient, notifyManager } from '@tanstack/query-core'
12import { signalProxy } from './signal-proxy'
13import { shouldThrowError } from './util'
14import type {
15 QueryKey,
16 QueryObserver,
17 QueryObserverResult,
18} from '@tanstack/query-core'
19import type { CreateBaseQueryOptions } from './types'
20β
21/**
22 * Base implementation for `injectQuery` and `injectInfiniteQuery`.
23 * @param optionsFn
24 * @param Observer
25 */
26export function createBaseQuery<
27 TQueryFnData,
28 TError,
29 TData,
30 TQueryData,
31 TQueryKey extends QueryKey,
32>(
33 optionsFn: () => CreateBaseQueryOptions<
34 TQueryFnData,
35 TError,
36 TData,
37 TQueryData,
38 TQueryKey
39 >,
40 Observer: typeof QueryObserver,
41) {
42 const ngZone = inject(NgZone)
43 const destroyRef = inject(DestroyRef)
44 const queryClient = inject(QueryClient)
45β
46 /**
47 * Signal that has the default options from query client applied
48 * computed() is used so signals can be inserted into the options
49 * making it reactive. Wrapping options in a function ensures embedded expressions
50 * are preserved and can keep being applied after signal changes
51 */
52 const defaultedOptionsSignal = computed(() => {
53 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
54 defaultedOptions._optimisticResults = 'optimistic'
55 return defaultedOptions
56 })
57β
58 const observerSignal = (() => {
59 let instance: QueryObserver<
60 TQueryFnData,
61 TError,
62 TData,
63 TQueryData,
64 TQueryKey
65 > | null = null
66β
67 return computed(() => {
68 return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
69 })
70 })()
71β
72 const optimisticResultSignal = computed(() =>
73 observerSignal().getOptimisticResult(defaultedOptionsSignal()),
74 )
75β
76 const resultFromSubscriberSignal = signal<QueryObserverResult<
77 TData,
78 TError
79 > | null>(null)
80β
81 effect(
82 (onCleanup) => {
83 const observer = observerSignal()
84 const defaultedOptions = defaultedOptionsSignal()
85β
86 untracked(() => {
87 observer.setOptions(defaultedOptions)
88 })
89 onCleanup(() => {
90 ngZone.run(() => resultFromSubscriberSignal.set(null))
91 })
92 },
93 {
94 // Set allowSignalWrites to support Angular < v19
95 // Set to undefined to avoid warning on newer versions
96 allowSignalWrites: VERSION.major < '19' || undefined,
97 },
98 )
99β
100 effect(() => {
101 // observer.trackResult is not used as this optimization is not needed for Angular
102 const observer = observerSignal()
103β
104 untracked(() => {
105 const unsubscribe = ngZone.runOutsideAngular(() =>
106 observer.subscribe(
107 notifyManager.batchCalls((state) => {
108 ngZone.run(() => {
109 if (
110 state.isError &&
111 !state.isFetching &&
112 // !isRestoring() && // todo: enable when client persistence is implemented
113 shouldThrowError(observer.options.throwOnError, [
114 state.error,
115 observer.getCurrentQuery(),
116 ])
117 ) {
118 ngZone.onError.emit(state.error)
119 throw state.error
120 }
121 resultFromSubscriberSignal.set(state)
122 })
123 }),
124 ),
125 )
126 destroyRef.onDestroy(unsubscribe)
127 })
128 })
129β
130 return signalProxy(
131 computed(() => {
132 const subscriberResult = resultFromSubscriberSignal()
133 const optimisticResult = optimisticResultSignal()
134 return subscriberResult ?? optimisticResult
135 }),
136 )
137}