Open History to see the last commit
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>
24}
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
41}
42β
43interface FailedAction<TError> {
44 type: 'failed'
45 failureCount: number
46 error: TError | null
47}
48β
49interface PendingAction<TVariables, TOnMutateResult> {
50 type: 'pending'
51 isPaused: boolean
52 variables?: TVariables
53 context?: TOnMutateResult
54}
55β
56interface SuccessAction<TData> {
57 type: 'success'
58 data: TData
59}
60β
61interface ErrorAction<TError> {
62 type: 'error'
63 error: TError
64}
65β
66interface PauseAction {
67 type: 'pause'
68}
69β
70interface ContinueAction {
71 type: 'continue'
72}
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, this.#client.isServer)
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 isServer: this.#client.isServer,
203 canRun: () => this.#mutationCache.canRun(this),
204 })
205β
206 const restored = this.state.status === 'pending'
207 const isPaused = !this.#retryer.canStart()
208β
209 try {
210 if (restored) {
211 // Dispatch continue action to unpause restored mutation
212 onContinue()
213 } else {
214 this.#dispatch({ type: 'pending', variables, isPaused })
215 // Notify cache callback
216 if (this.#mutationCache.config.onMutate) {
217 await this.#mutationCache.config.onMutate(
218 variables,
219 this as Mutation<unknown, unknown, unknown, unknown>,
220 mutationFnContext,
221 )
222 }
223 const context = await this.options.onMutate?.(
224 variables,
225 mutationFnContext,
226 )
227 if (context !== this.state.context) {
228 this.#dispatch({
229 type: 'pending',
230 context,
231 variables,
232 isPaused,
233 })
234 }
235 }
236 const data = await this.#retryer.start()
237β
238 // Notify cache callback
239 await this.#mutationCache.config.onSuccess?.(
240 data,
241 variables,
242 this.state.context,
243 this as Mutation<unknown, unknown, unknown, unknown>,
244 mutationFnContext,
245 )
246β
247 await this.options.onSuccess?.(
248 data,
249 variables,
250 this.state.context!,
251 mutationFnContext,
252 )
253β
254 // Notify cache callback
255 await this.#mutationCache.config.onSettled?.(
256 data,
257 null,
258 this.state.variables,
259 this.state.context,
260 this as Mutation<unknown, unknown, unknown, unknown>,
261 mutationFnContext,
262 )
263β
264 await this.options.onSettled?.(
265 data,
266 null,
267 variables,
268 this.state.context,
269 mutationFnContext,
270 )
271β
272 this.#dispatch({ type: 'success', data })
273 return data
274 } catch (error) {
275 try {
276 // Notify cache callback
277 await this.#mutationCache.config.onError?.(
278 error as any,
279 variables,
280 this.state.context,
281 this as Mutation<unknown, unknown, unknown, unknown>,
282 mutationFnContext,
283 )
284 } catch (e) {
285 void Promise.reject(e)
286 }
287β
288 try {
289 await this.options.onError?.(
290 error as TError,
291 variables,
292 this.state.context,
293 mutationFnContext,
294 )
295 } catch (e) {
296 void Promise.reject(e)
297 }
298β
299 try {
300 // Notify cache callback
301 await this.#mutationCache.config.onSettled?.(
302 undefined,
303 error as any,
304 this.state.variables,
305 this.state.context,
306 this as Mutation<unknown, unknown, unknown, unknown>,
307 mutationFnContext,
308 )
309 } catch (e) {
310 void Promise.reject(e)
311 }
312β
313 try {
314 await this.options.onSettled?.(
315 undefined,
316 error as TError,
317 variables,
318 this.state.context,
319 mutationFnContext,
320 )
321 } catch (e) {
322 void Promise.reject(e)
323 }
324β
325 this.#dispatch({ type: 'error', error: error as TError })
326 throw error
327 } finally {
328 this.#mutationCache.runNext(this)
329 }
330 }
331β
332 #dispatch(action: Action<TData, TError, TVariables, TOnMutateResult>): void {
333 const reducer = (
334 state: MutationState<TData, TError, TVariables, TOnMutateResult>,
335 ): MutationState<TData, TError, TVariables, TOnMutateResult> => {
336 switch (action.type) {
337 case 'failed':
338 return {
339 ...state,
340 failureCount: action.failureCount,
341 failureReason: action.error,
342 }
343 case 'pause':
344 return {
345 ...state,
346 isPaused: true,
347 }
348 case 'continue':
349 return {
350 ...state,
351 isPaused: false,
352 }
353 case 'pending':
354 return {
355 ...state,
356 context: action.context,
357 data: undefined,
358 failureCount: 0,
359 failureReason: null,
360 error: null,
361 isPaused: action.isPaused,
362 status: 'pending',
363 variables: action.variables,
364 submittedAt: Date.now(),
365 }
366 case 'success':
367 return {
368 ...state,
369 data: action.data,
370 failureCount: 0,
371 failureReason: null,
372 error: null,
373 status: 'success',
374 isPaused: false,
375 }
376 case 'error':
377 return {
378 ...state,
379 data: undefined,
380 error: action.error,
381 failureCount: state.failureCount + 1,
382 failureReason: action.error,
383 isPaused: false,
384 status: 'error',
385 }
386 }
387 }
388 this.state = reducer(this.state)
389β
390 notifyManager.batch(() => {
391 this.#observers.forEach((observer) => {
392 observer.onMutationUpdate(action)
393 })
394 this.#mutationCache.notify({
395 mutation: this,
396 type: 'updated',
397 action,
398 })
399 })
400 }
401}
402β
403export function getDefaultState<
404 TData,
405 TError,
406 TVariables,
407 TOnMutateResult,
408>(): MutationState<TData, TError, TVariables, TOnMutateResult> {
409 return {
410 context: undefined,
411 data: undefined,
412 error: null,
413 failureCount: 0,
414 failureReason: null,
415 isPaused: false,
416 status: 'idle',
417 variables: undefined,
418 submittedAt: 0,
419 }
420}