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

mutation.ts

403 lines9.8 KB

1import { notifyManager } from './notifyManager'
2import { Removable } from './removable'
3import { createRetryer } from './retryer'
4import type {
5 DefaultError,
6 MutationFunctionContext,
7 MutationMeta,
8 MutationOptions,
9 MutationStatus,
10} from './types'
11import type { MutationCache } from './mutationCache'
12import type { MutationObserver } from './mutationObserver'
13import type { Retryer } from './retryer'
14import type { QueryClient } from './queryClient'
15​
16// TYPES
17​
18interface MutationConfig<TData, TError, TVariables, TOnMutateResult> {
19 client: QueryClient
20 mutationId: number
21 mutationCache: MutationCache
22 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>
23 state?: MutationState<TData, TError, TVariables, TOnMutateResult>
25​
26export interface MutationState<
27 TData = unknown,
28 TError = DefaultError,
29 TVariables = unknown,
30 TOnMutateResult = unknown,
31> {
32 context: TOnMutateResult | undefined
33 data: TData | undefined
34 error: TError | null
35 failureCount: number
36 failureReason: TError | null
37 isPaused: boolean
38 status: MutationStatus
39 variables: TVariables | undefined
40 submittedAt: number
42​
43interface FailedAction<TError> {
44 type: 'failed'
45 failureCount: number
46 error: TError | null
48​
49interface PendingAction<TVariables, TOnMutateResult> {
50 type: 'pending'
51 isPaused: boolean
52 variables?: TVariables
53 context?: TOnMutateResult
55​
56interface SuccessAction<TData> {
57 type: 'success'
58 data: TData
60​
61interface ErrorAction<TError> {
62 type: 'error'
63 error: TError
65​
66interface PauseAction {
67 type: 'pause'
69​
70interface ContinueAction {
71 type: 'continue'
73​
74export type Action<TData, TError, TVariables, TOnMutateResult> =
75 | ContinueAction
76 | ErrorAction<TError>
77 | FailedAction<TError>
78 | PendingAction<TVariables, TOnMutateResult>
79 | PauseAction
80 | SuccessAction<TData>
81​
82// CLASS
83​
84export class Mutation<
85 TData = unknown,
86 TError = DefaultError,
87 TVariables = unknown,
88 TOnMutateResult = unknown,
89> extends Removable {
90 state: MutationState<TData, TError, TVariables, TOnMutateResult>
91 options!: MutationOptions<TData, TError, TVariables, TOnMutateResult>
92 readonly mutationId: number
93​
94 #client: QueryClient
95 #observers: Array<
96 MutationObserver<TData, TError, TVariables, TOnMutateResult>
97 >
98 #mutationCache: MutationCache
99 #retryer?: Retryer<TData>
100​
101 constructor(
102 config: MutationConfig<TData, TError, TVariables, TOnMutateResult>,
103 ) {
104 super()
105​
106 this.#client = config.client
107 this.mutationId = config.mutationId
108 this.#mutationCache = config.mutationCache
109 this.#observers = []
110 this.state = config.state || getDefaultState()
111​
112 this.setOptions(config.options)
113 this.scheduleGc()
114 }
115​
116 setOptions(
117 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
118 ): void {
119 this.options = options
120​
121 this.updateGcTime(this.options.gcTime)
122 }
123​
124 get meta(): MutationMeta | undefined {
125 return this.options.meta
126 }
127​
128 addObserver(observer: MutationObserver<any, any, any, any>): void {
129 if (!this.#observers.includes(observer)) {
130 this.#observers.push(observer)
131​
132 // Stop the mutation from being garbage collected
133 this.clearGcTimeout()
134​
135 this.#mutationCache.notify({
136 type: 'observerAdded',
137 mutation: this,
138 observer,
139 })
140 }
141 }
142​
143 removeObserver(observer: MutationObserver<any, any, any, any>): void {
144 this.#observers = this.#observers.filter((x) => x !== observer)
145​
146 this.scheduleGc()
147​
148 this.#mutationCache.notify({
149 type: 'observerRemoved',
150 mutation: this,
151 observer,
152 })
153 }
154​
155 protected optionalRemove() {
156 if (!this.#observers.length) {
157 if (this.state.status === 'pending') {
158 this.scheduleGc()
159 } else {
160 this.#mutationCache.remove(this)
161 }
162 }
163 }
164​
165 continue(): Promise<unknown> {
166 return (
167 this.#retryer?.continue() ??
168 // continuing a mutation assumes that variables are set, mutation must have been dehydrated before
169 this.execute(this.state.variables!)
170 )
171 }
172​
173 async execute(variables: TVariables): Promise<TData> {
174 const onContinue = () => {
175 this.#dispatch({ type: 'continue' })
176 }
177​
178 const mutationFnContext = {
179 client: this.#client,
180 meta: this.options.meta,
181 mutationKey: this.options.mutationKey,
182 } satisfies MutationFunctionContext
183​
184 this.#retryer = createRetryer({
185 fn: () => {
186 if (!this.options.mutationFn) {
187 return Promise.reject(new Error('No mutationFn found'))
188 }
189​
190 return this.options.mutationFn(variables, mutationFnContext)
191 },
192 onFail: (failureCount, error) => {
193 this.#dispatch({ type: 'failed', failureCount, error })
194 },
195 onPause: () => {
196 this.#dispatch({ type: 'pause' })
197 },
198 onContinue,
199 retry: this.options.retry ?? 0,
200 retryDelay: this.options.retryDelay,
201 networkMode: this.options.networkMode,
202 canRun: () => this.#mutationCache.canRun(this),
203 })
204​
205 const restored = this.state.status === 'pending'
206 const isPaused = !this.#retryer.canStart()
207​
208 try {
209 if (restored) {
210 // Dispatch continue action to unpause restored mutation
211 onContinue()
212 } else {
213 this.#dispatch({ type: 'pending', variables, isPaused })
214 // Notify cache callback
215 await this.#mutationCache.config.onMutate?.(
216 variables,
217 this as Mutation<unknown, unknown, unknown, unknown>,
218 mutationFnContext,
219 )
220 const context = await this.options.onMutate?.(
221 variables,
222 mutationFnContext,
223 )
224 if (context !== this.state.context) {
225 this.#dispatch({
226 type: 'pending',
227 context,
228 variables,
229 isPaused,
230 })
231 }
232 }
233 const data = await this.#retryer.start()
234​
235 // Notify cache callback
236 await this.#mutationCache.config.onSuccess?.(
237 data,
238 variables,
239 this.state.context,
240 this as Mutation<unknown, unknown, unknown, unknown>,
241 mutationFnContext,
242 )
243​
244 await this.options.onSuccess?.(
245 data,
246 variables,
247 this.state.context!,
248 mutationFnContext,
249 )
250​
251 // Notify cache callback
252 await this.#mutationCache.config.onSettled?.(
253 data,
254 null,
255 this.state.variables,
256 this.state.context,
257 this as Mutation<unknown, unknown, unknown, unknown>,
258 mutationFnContext,
259 )
260​
261 await this.options.onSettled?.(
262 data,
263 null,
264 variables,
265 this.state.context,
266 mutationFnContext,
267 )
268​
269 this.#dispatch({ type: 'success', data })
270 return data
271 } catch (error) {
272 try {
273 // Notify cache callback
274 await this.#mutationCache.config.onError?.(
275 error as any,
276 variables,
277 this.state.context,
278 this as Mutation<unknown, unknown, unknown, unknown>,
279 mutationFnContext,
280 )
281​
282 await this.options.onError?.(
283 error as TError,
284 variables,
285 this.state.context,
286 mutationFnContext,
287 )
288​
289 // Notify cache callback
290 await this.#mutationCache.config.onSettled?.(
291 undefined,
292 error as any,
293 this.state.variables,
294 this.state.context,
295 this as Mutation<unknown, unknown, unknown, unknown>,
296 mutationFnContext,
297 )
298​
299 await this.options.onSettled?.(
300 undefined,
301 error as TError,
302 variables,
303 this.state.context,
304 mutationFnContext,
305 )
306 throw error
307 } finally {
308 this.#dispatch({ type: 'error', error: error as TError })
309 }
310 } finally {
311 this.#mutationCache.runNext(this)
312 }
313 }
314​
315 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
316 const reducer = (
317 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
318 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
319 switch (action.type) {
320 case 'failed':
321 return {
322 ...state,
323 failureCount: action.failureCount,
324 failureReason: action.error,
325 }
326 case 'pause':
327 return {
328 ...state,
329 isPaused: true,
330 }
331 case 'continue':
332 return {
333 ...state,
334 isPaused: false,
335 }
336 case 'pending':
337 return {
338 ...state,
339 context: action.context,
340 data: undefined,
341 failureCount: 0,
342 failureReason: null,
343 error: null,
344 isPaused: action.isPaused,
345 status: 'pending',
346 variables: action.variables,
347 submittedAt: Date.now(),
348 }
349 case 'success':
350 return {
351 ...state,
352 data: action.data,
353 failureCount: 0,
354 failureReason: null,
355 error: null,
356 status: 'success',
357 isPaused: false,
358 }
359 case 'error':
360 return {
361 ...state,
362 data: undefined,
363 error: action.error,
364 failureCount: state.failureCount + 1,
365 failureReason: action.error,
366 isPaused: false,
367 status: 'error',
368 }
369 }
370 }
371 this.state = reducer(this.state)
372​
373 notifyManager.batch(() => {
374 this.#observers.forEach((observer) => {
375 observer.onMutationUpdate(action)
376 })
377 this.#mutationCache.notify({
378 mutation: this,
379 type: 'updated',
380 action,
381 })
382 })
383 }
385​
386export function getDefaultState<
387 TData,
388 TError,
389 TVariables,
390 TOnMutateResult,
391>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
392 return {
393 context: undefined,
394 data: undefined,
395 error: null,
396 failureCount: 0,
397 failureReason: null,
398 isPaused: false,
399 status: 'idle',
400 variables: undefined,
401 submittedAt: 0,
402 }