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

inject-mutation.ts

171 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 TContext = unknown,
49>(
50 injectMutationFn: () => CreateMutationOptions<
51 TData,
52 TError,
53 TVariables,
54 TContext
55 >,
56 options?: InjectMutationOptions,
57): CreateMutationResult<TData, TError, TVariables, TContext> {
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<TData, TError, TVariables, TContext> | null =
73 null
74​
75 return computed(() => {
76 return (instance ||= new MutationObserver(queryClient, optionsSignal()))
77 })
78 })()
79​
80 const mutateFnSignal = computed<
81 CreateMutateFunction<TData, TError, TVariables, TContext>
82 >(() => {
83 const observer = observerSignal()
84 return (variables, mutateOptions) => {
85 observer.mutate(variables, mutateOptions).catch(noop)
86 }
87 })
88​
89 /**
90 * Computed signal that gets result from mutation cache based on passed options
91 */
92 const resultFromInitialOptionsSignal = computed(() => {
93 const observer = observerSignal()
94 return observer.getCurrentResult()
95 })
96​
97 /**
98 * Signal that contains result set by subscriber
99 */
100 const resultFromSubscriberSignal = signal<MutationObserverResult<
101 TData,
102 TError,
103 TVariables,
104 TContext
105 > | null>(null)
106​
107 effect(
108 () => {
109 const observer = observerSignal()
110 const observerOptions = optionsSignal()
111​
112 untracked(() => {
113 observer.setOptions(observerOptions)
114 })
115 },
116 {
117 injector,
118 },
119 )
120​
121 effect(
122 () => {
123 // observer.trackResult is not used as this optimization is not needed for Angular
124 const observer = observerSignal()
125​
126 untracked(() => {
127 const unsubscribe = ngZone.runOutsideAngular(() =>
128 observer.subscribe(
129 notifyManager.batchCalls((state) => {
130 ngZone.run(() => {
131 if (
132 state.isError &&
133 shouldThrowError(observer.options.throwOnError, [state.error])
134 ) {
135 ngZone.onError.emit(state.error)
136 throw state.error
137 }
138​
139 resultFromSubscriberSignal.set(state)
140 })
141 }),
142 ),
143 )
144 destroyRef.onDestroy(unsubscribe)
145 })
146 },
147 {
148 injector,
149 },
150 )
151​
152 const resultSignal = computed(() => {
153 const resultFromSubscriber = resultFromSubscriberSignal()
154 const resultFromInitialOptions = resultFromInitialOptionsSignal()
155​
156 const result = resultFromSubscriber ?? resultFromInitialOptions
157​
158 return {
159 ...result,
160 mutate: mutateFnSignal(),
161 mutateAsync: result.mutate,
162 }
163 })
164​
165 return signalProxy(resultSignal) as CreateMutationResult<
166 TData,
167 TError,
168 TVariables,
169 TContext
170 >