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

mutation.ts

335 lines8.2 KB

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