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

mutation.ts

349 lines8.5 KB

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