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

create-base-query.ts

139 lines3.7 KB

1import {
2 NgZone,
3 VERSION,
4 computed,
5 effect,
6 inject,
7 signal,
8 untracked,
9} from '@angular/core'
10import { QueryClient, notifyManager } from '@tanstack/query-core'
11import { signalProxy } from './signal-proxy'
12import { shouldThrowError } from './util'
13import { injectIsRestoring } from './inject-is-restoring'
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 queryClient = inject(QueryClient)
44 const isRestoring = injectIsRestoring()
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 = isRestoring()
55 ? 'isRestoring'
56 : '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 })
91 onCleanup(() => {
92 ngZone.run(() => resultFromSubscriberSignal.set(null))
93 })
94 },
95 {
96 // Set allowSignalWrites to support Angular < v19
97 // Set to undefined to avoid warning on newer versions
98 allowSignalWrites: VERSION.major < '19' || undefined,
99 },
100 )
101​
102 effect((onCleanup) => {
103 // observer.trackResult is not used as this optimization is not needed for Angular
104 const observer = observerSignal()
105 const unsubscribe = isRestoring()
106 ? () => undefined
107 : untracked(() =>
108 ngZone.runOutsideAngular(() =>
109 observer.subscribe(
110 notifyManager.batchCalls((state) => {
111 ngZone.run(() => {
112 if (
113 state.isError &&
114 !state.isFetching &&
115 shouldThrowError(observer.options.throwOnError, [
116 state.error,
117 observer.getCurrentQuery(),
118 ])
119 ) {
120 ngZone.onError.emit(state.error)
121 throw state.error
122 }
123 resultFromSubscriberSignal.set(state)
124 })
125 }),
126 ),
127 ),
128 )
129 onCleanup(unsubscribe)
130 })
131​
132 return signalProxy(
133 computed(() => {
134 const subscriberResult = resultFromSubscriberSignal()
135 const optimisticResult = optimisticResultSignal()
136 return subscriberResult ?? optimisticResult
137 }),
138 )