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