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

mutation.ts

383 lines9.6 KB

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