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

inject-mutation.ts

175 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 */
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 destroyRef = injector.get(DestroyRef)
61 const ngZone = injector.get(NgZone)
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 () => {
127 // observer.trackResult is not used as this optimization is not needed for Angular
128 const observer = observerSignal()
129​
130 untracked(() => {
131 const unsubscribe = ngZone.runOutsideAngular(() =>
132 observer.subscribe(
133 notifyManager.batchCalls((state) => {
134 ngZone.run(() => {
135 if (
136 state.isError &&
137 shouldThrowError(observer.options.throwOnError, [state.error])
138 ) {
139 ngZone.onError.emit(state.error)
140 throw state.error
141 }
142​
143 resultFromSubscriberSignal.set(state)
144 })
145 }),
146 ),
147 )
148 destroyRef.onDestroy(unsubscribe)
149 })
150 },
151 {
152 injector,
153 },
154 )
155​
156 const resultSignal = computed(() => {
157 const resultFromSubscriber = resultFromSubscriberSignal()
158 const resultFromInitialOptions = resultFromInitialOptionsSignal()
159​
160 const result = resultFromSubscriber ?? resultFromInitialOptions
161​
162 return {
163 ...result,
164 mutate: mutateFnSignal(),
165 mutateAsync: result.mutate,
166 }
167 })
168​
169 return signalProxy(resultSignal) as CreateMutationResult<
170 TData,
171 TError,
172 TVariables,
173 TOnMutateResult
174 >