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

inject-mutation.ts

163 lines4.4 KB

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