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

create-base-query.ts

143 lines3.8 KB

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