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

inject-mutation.ts

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