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

mutation.ts

362 lines9.0 KB

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