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

mutation.ts

366 lines9.0 KB

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