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

inject-mutation.ts

193 lines4.9 KB

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
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 = (() => {
72 let instance: MutationObserver<
73 TData,
74 TError,
75 TVariables,
76 TOnMutateResult
77 > | null = null
78​
79 return computed(() => {
80 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
81 })
82 })()
83​
84 const mutateFnSignal = computed<
85 CreateMutateFunction<TData, TError, TVariables, TOnMutateResult>
86 >(() => {
87 const observer = observerSignal()
88 return (variables, mutateOptions) => {
89 observer.mutate(variables, mutateOptions).catch(noop)
90 }
91 })
92​
93 /**
94 * Computed signal that gets result from mutation cache based on passed options
95 */
96 const resultFromInitialOptionsSignal = computed(() => {
97 const observer = observerSignal()
98 return observer.getCurrentResult()
99 })
100​
101 /**
102 * Signal that contains result set by subscriber
103 */
104 const resultFromSubscriberSignal = signal<MutationObserverResult<
105 TData,
106 TError,
107 TVariables,
108 TOnMutateResult
109 > | null>(null)
110​
111 effect(
112 () => {
113 const observer = observerSignal()
114 const observerOptions = optionsSignal()
115​
116 untracked(() => {
117 observer.setOptions(observerOptions)
118 })
119 },
120 {
121 injector,
122 },
123 )
124​
125 effect(
126 (onCleanup) => {
127 const observer = observerSignal()
128 let taskCleanupRef: (() => void) | null = null
129​
130 untracked(() => {
131 const unsubscribe = ngZone.runOutsideAngular(() =>
132 observer.subscribe(
133 notifyManager.batchCalls((state) => {
134 ngZone.run(() => {
135 // Track pending task when mutation is pending
136 if (state.isPending && !taskCleanupRef) {
137 taskCleanupRef = pendingTasks.add()
138 }
139​
140 // Clear pending task when mutation is no longer pending
141 if (!state.isPending && taskCleanupRef) {
142 taskCleanupRef()
143 taskCleanupRef = null
144 }
145​
146 if (
147 state.isError &&
148 shouldThrowError(observer.options.throwOnError, [state.error])
149 ) {
150 ngZone.onError.emit(state.error)
151 throw state.error
152 }
153​
154 resultFromSubscriberSignal.set(state)
155 })
156 }),
157 ),
158 )
159 onCleanup(() => {
160 // Clean up any pending task on destroy
161 if (taskCleanupRef) {
162 taskCleanupRef()
163 taskCleanupRef = null
164 }
165 unsubscribe()
166 })
167 })
168 },
169 {
170 injector,
171 },
172 )
173​
174 const resultSignal = computed(() => {
175 const resultFromSubscriber = resultFromSubscriberSignal()
176 const resultFromInitialOptions = resultFromInitialOptionsSignal()
177​
178 const result = resultFromSubscriber ?? resultFromInitialOptions
179​
180 return {
181 ...result,
182 mutate: mutateFnSignal(),
183 mutateAsync: result.mutate,
184 }
185 })
186​
187 return signalProxy(resultSignal) as CreateMutationResult<
188 TData,
189 TError,
190 TVariables,
191 TOnMutateResult
192 >