Open History to see the last commit
1import {
2 Injector,
3 NgZone,
4 PendingTasks,
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
34}
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 */
44export function injectMutation<
45 TData = unknown,
46 TError = DefaultError,
47 TVariables = void,
48 TOnMutateResult = unknown,
49>(
50 injectMutationFn: () => CreateMutationOptions<
51 TData,
52 TError,
53 TVariables,
54 TOnMutateResult
55 >,
56 options?: InjectMutationOptions,
57): CreateMutationResult<TData, TError, TVariables, TOnMutateResult> {
58 !options?.injector && assertInInjectionContext(injectMutation)
59 const injector = options?.injector ?? inject(Injector)
60 const ngZone = injector.get(NgZone)
61 const pendingTasks = injector.get(PendingTasks)
62 const queryClient = injector.get(QueryClient)
63β
64 /**
65 * computed() is used so signals can be inserted into the options
66 * making it reactive. Wrapping options in a function ensures embedded expressions
67 * are preserved and can keep being applied after signal changes
68 */
69 const optionsSignal = computed(injectMutationFn)
70β
71 const observerSignal = computed(() => new MutationObserver(queryClient, untracked(optionsSignal)))
72β
73 let destroyed = false
74 let taskCleanupRef: (() => void) | null = null
75β
76 const startPendingTask = () => {
77 if (!taskCleanupRef && !destroyed) {
78 taskCleanupRef = pendingTasks.add()
79 }
80 }
81β
82 const stopPendingTask = () => {
83 if (taskCleanupRef) {
84 taskCleanupRef()
85 taskCleanupRef = null
86 }
87 }
88β
89 const mutateFnSignal = computed<
90 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
91 >(() => {
92 const observer = observerSignal()
93 return (variables, mutateOptions) => {
94 observer.mutate(variables, mutateOptions).catch(noop)
95 }
96 })
97β
98 /**
99 * Computed signal that gets result from mutation cache based on passed options
100 */
101 const resultFromInitialOptionsSignal = computed(() => {
102 const observer = observerSignal()
103 return observer.getCurrentResult()
104 })
105β
106 /**
107 * Signal that contains result set by subscriber
108 */
109 const resultFromSubscriberSignal = signal<MutationObserverResult<
110 TData,
111 TError,
112 TVariables,
113 TOnMutateResult
114 > | null>(null)
115β
116 effect(
117 () => {
118 const observer = observerSignal()
119 const observerOptions = optionsSignal()
120β
121 untracked(() => {
122 observer.setOptions(observerOptions)
123 })
124 },
125 {
126 injector,
127 },
128 )
129β
130 effect(
131 (onCleanup) => {
132 const observer = observerSignal()
133β
134 untracked(() => {
135 const unsubscribe = ngZone.runOutsideAngular(() =>
136 observer.subscribe(
137 notifyManager.batchCalls((state) => {
138 ngZone.run(() => {
139 if (destroyed) return
140β
141 if (state.isPending) {
142 startPendingTask()
143 } else {
144 stopPendingTask()
145 }
146β
147 if (
148 state.isError &&
149 shouldThrowError(observer.options.throwOnError, [state.error])
150 ) {
151 ngZone.onError.emit(state.error)
152 throw state.error
153 }
154β
155 resultFromSubscriberSignal.set(state)
156 })
157 }),
158 ),
159 )
160 onCleanup(() => {
161 destroyed = true
162 stopPendingTask()
163 unsubscribe()
164 })
165 })
166 },
167 {
168 injector,
169 },
170 )
171β
172 const resultSignal = computed(() => {
173 const resultFromSubscriber = resultFromSubscriberSignal()
174 const resultFromInitialOptions = resultFromInitialOptionsSignal()
175β
176 const result = resultFromSubscriber ?? resultFromInitialOptions
177β
178 return {
179 ...result,
180 mutate: mutateFnSignal(),
181 mutateAsync: result.mutate,
182 }
183 })
184β
185 return signalProxy(resultSignal, [
186 'mutate',
187 'mutateAsync',
188 'reset',
189 ]) as CreateMutationResult<TData, TError, TVariables, TOnMutateResult>
190}