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

mutation.ts

417 lines10.1 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 } catch (e) {
282 void Promise.reject(e)
283 }
284​
285 try {
286 await this.options.onError?.(
287 error as TError,
288 variables,
289 this.state.context,
290 mutationFnContext,
291 )
292 } catch (e) {
293 void Promise.reject(e)
294 }
295​
296 try {
297 // Notify cache callback
298 await this.#mutationCache.config.onSettled?.(
299 undefined,
300 error as any,
301 this.state.variables,
302 this.state.context,
303 this as Mutation<unknown, unknown, unknown, unknown>,
304 mutationFnContext,
305 )
306 } catch (e) {
307 void Promise.reject(e)
308 }
309​
310 try {
311 await this.options.onSettled?.(
312 undefined,
313 error as TError,
314 variables,
315 this.state.context,
316 mutationFnContext,
317 )
318 } catch (e) {
319 void Promise.reject(e)
320 }
321​
322 this.#dispatch({ type: 'error', error: error as TError })
323 throw error
324 } finally {
325 this.#mutationCache.runNext(this)
326 }
327 }
328​
329 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
330 const reducer = (
331 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
332 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
333 switch (action.type) {
334 case 'failed':
335 return {
336 ...state,
337 failureCount: action.failureCount,
338 failureReason: action.error,
339 }
340 case 'pause':
341 return {
342 ...state,
343 isPaused: true,
344 }
345 case 'continue':
346 return {
347 ...state,
348 isPaused: false,
349 }
350 case 'pending':
351 return {
352 ...state,
353 context: action.context,
354 data: undefined,
355 failureCount: 0,
356 failureReason: null,
357 error: null,
358 isPaused: action.isPaused,
359 status: 'pending',
360 variables: action.variables,
361 submittedAt: Date.now(),
362 }
363 case 'success':
364 return {
365 ...state,
366 data: action.data,
367 failureCount: 0,
368 failureReason: null,
369 error: null,
370 status: 'success',
371 isPaused: false,
372 }
373 case 'error':
374 return {
375 ...state,
376 data: undefined,
377 error: action.error,
378 failureCount: state.failureCount + 1,
379 failureReason: action.error,
380 isPaused: false,
381 status: 'error',
382 }
383 }
384 }
385 this.state = reducer(this.state)
386​
387 notifyManager.batch(() => {
388 this.#observers.forEach((observer) => {
389 observer.onMutationUpdate(action)
390 })
391 this.#mutationCache.notify({
392 mutation: this,
393 type: 'updated',
394 action,
395 })
396 })
397 }
399​
400export function getDefaultState<
401 TData,
402 TError,
403 TVariables,
404 TOnMutateResult,
405>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
406 return {
407 context: undefined,
408 data: undefined,
409 error: null,
410 failureCount: 0,
411 failureReason: null,
412 isPaused: false,
413 status: 'idle',
414 variables: undefined,
415 submittedAt: 0,
416 }