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

create-base-query.ts

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