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

inject-mutation.ts

172 lines4.3 KB

1import {
2 DestroyRef,
3 Injector,
4 NgZone,
5 assertInInjectionContext,
6 computed,
7 effect,
8 inject,
9 signal,
10 untracked,
11} from '@angular/core'
12import {
13 MutationObserver,
14 QueryClient,
15 noop,
16 notifyManager,
17 shouldThrowError,
18} from '@tanstack/query-core'
19import { signalProxy } from './signal-proxy'
20import type { DefaultError, MutationObserverResult } from '@tanstack/query-core'
21import type {
22 CreateMutateFunction,
23 CreateMutationOptions,
24 CreateMutationResult,
25} from './types'
26​
27export interface InjectMutationOptions {
28 /**
29 * The `Injector` in which to create the mutation.
30 *
31 * If this is not provided, the current injection context will be used instead (via `inject`).
32 */
33 injector?: Injector
35​
36/**
37 * Injects a mutation: an imperative function that can be invoked which typically performs server side effects.
38 *
39 * Unlike queries, mutations are not run automatically.
40 * @param injectMutationFn - A function that returns mutation options.
41 * @param options - Additional configuration
42 * @returns The mutation.
43 * @public
44 */
45export function injectMutation<
46 TData = unknown,
47 TError = DefaultError,
48 TVariables = void,
49 TContext = unknown,
50>(
51 injectMutationFn: () => CreateMutationOptions<
52 TData,
53 TError,
54 TVariables,
55 TContext
56 >,
57 options?: InjectMutationOptions,
58): CreateMutationResult<TData, TError, TVariables, TContext> {
59 !options?.injector && assertInInjectionContext(injectMutation)
60 const injector = options?.injector ?? inject(Injector)
61 const destroyRef = injector.get(DestroyRef)
62 const ngZone = injector.get(NgZone)
63 const queryClient = injector.get(QueryClient)
64​
65 /**
66 * computed() is used so signals can be inserted into the options
67 * making it reactive. Wrapping options in a function ensures embedded expressions
68 * are preserved and can keep being applied after signal changes
69 */
70 const optionsSignal = computed(injectMutationFn)
71​
72 const observerSignal = (() => {
73 let instance: MutationObserver<TData, TError, TVariables, TContext> | null =
74 null
75​
76 return computed(() => {
77 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
78 })
79 })()
80​
81 const mutateFnSignal = computed<
82 CreateMutateFunction<TData, TError, TVariables, TContext>
83 >(() => {
84 const observer = observerSignal()
85 return (variables, mutateOptions) => {
86 observer.mutate(variables, mutateOptions).catch(noop)
87 }
88 })
89​
90 /**
91 * Computed signal that gets result from mutation cache based on passed options
92 */
93 const resultFromInitialOptionsSignal = computed(() => {
94 const observer = observerSignal()
95 return observer.getCurrentResult()
96 })
97​
98 /**
99 * Signal that contains result set by subscriber
100 */
101 const resultFromSubscriberSignal = signal<MutationObserverResult<
102 TData,
103 TError,
104 TVariables,
105 TContext
106 > | null>(null)
107​
108 effect(
109 () => {
110 const observer = observerSignal()
111 const observerOptions = optionsSignal()
112​
113 untracked(() => {
114 observer.setOptions(observerOptions)
115 })
116 },
117 {
118 injector,
119 },
120 )
121​
122 effect(
123 () => {
124 // observer.trackResult is not used as this optimization is not needed for Angular
125 const observer = observerSignal()
126​
127 untracked(() => {
128 const unsubscribe = ngZone.runOutsideAngular(() =>
129 observer.subscribe(
130 notifyManager.batchCalls((state) => {
131 ngZone.run(() => {
132 if (
133 state.isError &&
134 shouldThrowError(observer.options.throwOnError, [state.error])
135 ) {
136 ngZone.onError.emit(state.error)
137 throw state.error
138 }
139​
140 resultFromSubscriberSignal.set(state)
141 })
142 }),
143 ),
144 )
145 destroyRef.onDestroy(unsubscribe)
146 })
147 },
148 {
149 injector,
150 },
151 )
152​
153 const resultSignal = computed(() => {
154 const resultFromSubscriber = resultFromSubscriberSignal()
155 const resultFromInitialOptions = resultFromInitialOptionsSignal()
156​
157 const result = resultFromSubscriber ?? resultFromInitialOptions
158​
159 return {
160 ...result,
161 mutate: mutateFnSignal(),
162 mutateAsync: result.mutate,
163 }
164 })
165​
166 return signalProxy(resultSignal) as CreateMutationResult<
167 TData,
168 TError,
169 TVariables,
170 TContext
171 >