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

create-base-query.ts

138 lines3.7 KB

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 */
24export function createBaseQuery<
25 TQueryFnData,
26 TError,
27 TData,
28 TQueryData,
29 TQueryKey extends QueryKey,
30>(
31 optionsFn: () => CreateBaseQueryOptions<
32 TQueryFnData,
33 TError,
34 TData,
35 TQueryData,
36 TQueryKey
37 >,
38 Observer: typeof QueryObserver,
39) {
40 const ngZone = inject(NgZone)
41 const destroyRef = inject(DestroyRef)
42 const queryClient = inject(QueryClient)
43​
44 /**
45 * Signal that has the default options from query client applied
46 * computed() is used so signals can be inserted into the options
47 * making it reactive. Wrapping options in a function ensures embedded expressions
48 * are preserved and can keep being applied after signal changes
49 */
50 const defaultedOptionsSignal = computed(() => {
51 const defaultedOptions = queryClient.defaultQueryOptions(optionsFn())
52 defaultedOptions._optimisticResults = 'optimistic'
53 return defaultedOptions
54 })
55​
56 const observerSignal = (() => {
57 let instance: QueryObserver<
58 TQueryFnData,
59 TError,
60 TData,
61 TQueryData,
62 TQueryKey
63 > | null = null
64​
65 return computed(() => {
66 return (instance ||= new Observer(queryClient, defaultedOptionsSignal()))
67 })
68 })()
69​
70 const optimisticResultSignal = computed(() =>
71 observerSignal().getOptimisticResult(defaultedOptionsSignal()),
72 )
73​
74 const resultFromSubscriberSignal = signal<QueryObserverResult<
75 TData,
76 TError
77 > | null>(null)
78​
79 effect(
80 (onCleanup) => {
81 const observer = observerSignal()
82 const defaultedOptions = defaultedOptionsSignal()
83​
84 untracked(() => {
85 observer.setOptions(defaultedOptions, {
86 // Do not notify on updates because of changes in the options because
87 // these changes should already be reflected in the optimistic result.
88 listeners: false,
89 })
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(() => {
103 // observer.trackResult is not used as this optimization is not needed for Angular
104 const observer = observerSignal()
105​
106 untracked(() => {
107 const unsubscribe = ngZone.runOutsideAngular(() =>
108 observer.subscribe(
109 notifyManager.batchCalls((state) => {
110 ngZone.run(() => {
111 if (
112 state.isError &&
113 !state.isFetching &&
114 // !isRestoring() && // todo: enable when client persistence is implemented
115 shouldThrowError(observer.options.throwOnError, [
116 state.error,
117 observer.getCurrentQuery(),
118 ])
119 ) {
120 throw state.error
121 }
122 resultFromSubscriberSignal.set(state)
123 })
124 }),
125 ),
126 )
127 destroyRef.onDestroy(unsubscribe)
128 })
129 })
130​
131 return signalProxy(
132 computed(() => {
133 const subscriberResult = resultFromSubscriberSignal()
134 const optimisticResult = optimisticResultSignal()
135 return subscriberResult ?? optimisticResult
136 }),
137 )