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

mutation.ts

427 lines10.5 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 // a settled mutation has no retryer to continue and must not run again
170 (this.state.status === 'pending'
171 ? this.execute(this.state.variables!)
172 : Promise.resolve())
173 )
174 }
175​
176 async execute(variables: TVariables): Promise<TData> {
177 const onContinue = () => {
178 this.#dispatch({ type: 'continue' })
179 }
180​
181 const mutationFnContext = {
182 client: this.#client,
183 meta: this.options.meta,
184 mutationKey: this.options.mutationKey,
185 } satisfies MutationFunctionContext
186​
187 const retryer = (this.#retryer = createRetryer({
188 fn: () => {
189 if (!this.options.mutationFn) {
190 return Promise.reject(new Error('No mutationFn found'))
191 }
192​
193 return this.options.mutationFn(variables, mutationFnContext)
194 },
195 onFail: (failureCount, error) => {
196 this.#dispatch({ type: 'failed', failureCount, error })
197 },
198 onPause: () => {
199 this.#dispatch({ type: 'pause' })
200 },
201 onContinue,
202 retry: this.options.retry ?? 0,
203 retryDelay: this.options.retryDelay,
204 networkMode: this.options.networkMode,
205 canRun: () => this.#mutationCache.canRun(this),
206 }))
207​
208 const restored = this.state.status === 'pending'
209 const isPaused = !retryer.canStart()
210​
211 try {
212 if (restored) {
213 // Dispatch continue action to unpause restored mutation
214 onContinue()
215 } else {
216 this.#dispatch({ type: 'pending', variables, isPaused })
217 // Notify cache callback
218 if (this.#mutationCache.config.onMutate) {
219 await this.#mutationCache.config.onMutate(
220 variables,
221 this as Mutation<unknown, unknown, unknown, unknown>,
222 mutationFnContext,
223 )
224 }
225 const context = await this.options.onMutate?.(
226 variables,
227 mutationFnContext,
228 )
229 if (context !== this.state.context) {
230 this.#dispatch({
231 type: 'pending',
232 context,
233 variables,
234 isPaused,
235 })
236 }
237 }
238 const data = await retryer.start()
239​
240 // Notify cache callback
241 await this.#mutationCache.config.onSuccess?.(
242 data,
243 variables,
244 this.state.context,
245 this as Mutation<unknown, unknown, unknown, unknown>,
246 mutationFnContext,
247 )
248​
249 await this.options.onSuccess?.(
250 data,
251 variables,
252 this.state.context!,
253 mutationFnContext,
254 )
255​
256 // Notify cache callback
257 await this.#mutationCache.config.onSettled?.(
258 data,
259 null,
260 this.state.variables,
261 this.state.context,
262 this as Mutation<unknown, unknown, unknown, unknown>,
263 mutationFnContext,
264 )
265​
266 await this.options.onSettled?.(
267 data,
268 null,
269 variables,
270 this.state.context,
271 mutationFnContext,
272 )
273​
274 this.#dispatch({ type: 'success', data })
275 return data
276 } catch (error) {
277 try {
278 // Notify cache callback
279 await this.#mutationCache.config.onError?.(
280 error as any,
281 variables,
282 this.state.context,
283 this as Mutation<unknown, unknown, unknown, unknown>,
284 mutationFnContext,
285 )
286 } catch (e) {
287 void Promise.reject(e)
288 }
289​
290 try {
291 await this.options.onError?.(
292 error as TError,
293 variables,
294 this.state.context,
295 mutationFnContext,
296 )
297 } catch (e) {
298 void Promise.reject(e)
299 }
300​
301 try {
302 // Notify cache callback
303 await this.#mutationCache.config.onSettled?.(
304 undefined,
305 error as any,
306 this.state.variables,
307 this.state.context,
308 this as Mutation<unknown, unknown, unknown, unknown>,
309 mutationFnContext,
310 )
311 } catch (e) {
312 void Promise.reject(e)
313 }
314​
315 try {
316 await this.options.onSettled?.(
317 undefined,
318 error as TError,
319 variables,
320 this.state.context,
321 mutationFnContext,
322 )
323 } catch (e) {
324 void Promise.reject(e)
325 }
326​
327 this.#dispatch({ type: 'error', error: error as TError })
328 throw error
329 } finally {
330 // The settled retryer's promise would otherwise pin this mutation's
331 // result, variables and context for as long as the cache keeps it
332 if (this.#retryer === retryer) {
333 this.#retryer = undefined
334 }
335 this.#mutationCache.runNext(this)
336 }
337 }
338​
339 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
340 const reducer = (
341 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
342 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
343 switch (action.type) {
344 case 'failed':
345 return {
346 ...state,
347 failureCount: action.failureCount,
348 failureReason: action.error,
349 }
350 case 'pause':
351 return {
352 ...state,
353 isPaused: true,
354 }
355 case 'continue':
356 return {
357 ...state,
358 isPaused: false,
359 }
360 case 'pending':
361 return {
362 ...state,
363 context: action.context,
364 data: undefined,
365 failureCount: 0,
366 failureReason: null,
367 error: null,
368 isPaused: action.isPaused,
369 status: 'pending',
370 variables: action.variables,
371 submittedAt: Date.now(),
372 }
373 case 'success':
374 return {
375 ...state,
376 data: action.data,
377 failureCount: 0,
378 failureReason: null,
379 error: null,
380 status: 'success',
381 isPaused: false,
382 }
383 case 'error':
384 return {
385 ...state,
386 data: undefined,
387 error: action.error,
388 failureCount: state.failureCount + 1,
389 failureReason: action.error,
390 isPaused: false,
391 status: 'error',
392 }
393 }
394 }
395 this.state = reducer(this.state)
396​
397 notifyManager.batch(() => {
398 this.#observers.forEach((observer) => {
399 observer.onMutationUpdate(action)
400 })
401 this.#mutationCache.notify({
402 mutation: this,
403 type: 'updated',
404 action,
405 })
406 })
407 }
409​
410export function getDefaultState<
411 TData,
412 TError,
413 TVariables,
414 TOnMutateResult,
415>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
416 return {
417 context: undefined,
418 data: undefined,
419 error: null,
420 failureCount: 0,
421 failureReason: null,
422 isPaused: false,
423 status: 'idle',
424 variables: undefined,
425 submittedAt: 0,
426 }