Open History to see the last commit
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>
21}
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
38}
39β
40interface FailedAction<TError> {
41 type: 'failed'
42 failureCount: number
43 error: TError | null
44}
45β
46interface PendingAction<TVariables, TContext> {
47 type: 'pending'
48 isPaused: boolean
49 variables?: TVariables
50 context?: TContext
51}
52β
53interface SuccessAction<TData> {
54 type: 'success'
55 data: TData
56}
57β
58interface ErrorAction<TError> {
59 type: 'error'
60 error: TError
61}
62β
63interface PauseAction {
64 type: 'pause'
65}
66β
67interface ContinueAction {
68 type: 'continue'
69}
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 this.#retryer = createRetryer({
166 fn: () => {
167 if (!this.options.mutationFn) {
168 return Promise.reject(new Error('No mutationFn found'))
169 }
170 return this.options.mutationFn(variables)
171 },
172 onFail: (failureCount, error) => {
173 this.#dispatch({ type: 'failed', failureCount, error })
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 canRun: () => this.#mutationCache.canRun(this),
185 })
186β
187 const restored = this.state.status === 'pending'
188 const isPaused = !this.#retryer.canStart()
189β
190 try {
191 if (!restored) {
192 this.#dispatch({ type: 'pending', variables, isPaused })
193 // Notify cache callback
194 await this.#mutationCache.config.onMutate?.(
195 variables,
196 this as Mutation<unknown, unknown, unknown, unknown>,
197 )
198 const context = await this.options.onMutate?.(variables)
199 if (context !== this.state.context) {
200 this.#dispatch({
201 type: 'pending',
202 context,
203 variables,
204 isPaused,
205 })
206 }
207 }
208 const data = await this.#retryer.start()
209β
210 // Notify cache callback
211 await this.#mutationCache.config.onSuccess?.(
212 data,
213 variables,
214 this.state.context,
215 this as Mutation<unknown, unknown, unknown, unknown>,
216 )
217β
218 await this.options.onSuccess?.(data, variables, this.state.context!)
219β
220 // Notify cache callback
221 await this.#mutationCache.config.onSettled?.(
222 data,
223 null,
224 this.state.variables,
225 this.state.context,
226 this as Mutation<unknown, unknown, unknown, unknown>,
227 )
228β
229 await this.options.onSettled?.(data, null, variables, this.state.context)
230β
231 this.#dispatch({ type: 'success', data })
232 return data
233 } catch (error) {
234 try {
235 // Notify cache callback
236 await this.#mutationCache.config.onError?.(
237 error as any,
238 variables,
239 this.state.context,
240 this as Mutation<unknown, unknown, unknown, unknown>,
241 )
242β
243 await this.options.onError?.(
244 error as TError,
245 variables,
246 this.state.context,
247 )
248β
249 // Notify cache callback
250 await this.#mutationCache.config.onSettled?.(
251 undefined,
252 error as any,
253 this.state.variables,
254 this.state.context,
255 this as Mutation<unknown, unknown, unknown, unknown>,
256 )
257β
258 await this.options.onSettled?.(
259 undefined,
260 error as TError,
261 variables,
262 this.state.context,
263 )
264 throw error
265 } finally {
266 this.#dispatch({ type: 'error', error: error as TError })
267 }
268 } finally {
269 this.#mutationCache.runNext(this)
270 }
271 }
272β
273 #dispatch(action: Action<TData, TError, TVariables, TContext>): void {
274 const reducer = (
275 state: MutationState<TData, TError, TVariables, TContext>,
276 ): MutationState<TData, TError, TVariables, TContext> => {
277 switch (action.type) {
278 case 'failed':
279 return {
280 ...state,
281 failureCount: action.failureCount,
282 failureReason: action.error,
283 }
284 case 'pause':
285 return {
286 ...state,
287 isPaused: true,
288 }
289 case 'continue':
290 return {
291 ...state,
292 isPaused: false,
293 }
294 case 'pending':
295 return {
296 ...state,
297 context: action.context,
298 data: undefined,
299 failureCount: 0,
300 failureReason: null,
301 error: null,
302 isPaused: action.isPaused,
303 status: 'pending',
304 variables: action.variables,
305 submittedAt: Date.now(),
306 }
307 case 'success':
308 return {
309 ...state,
310 data: action.data,
311 failureCount: 0,
312 failureReason: null,
313 error: null,
314 status: 'success',
315 isPaused: false,
316 }
317 case 'error':
318 return {
319 ...state,
320 data: undefined,
321 error: action.error,
322 failureCount: state.failureCount + 1,
323 failureReason: action.error,
324 isPaused: false,
325 status: 'error',
326 }
327 }
328 }
329 this.state = reducer(this.state)
330β
331 notifyManager.batch(() => {
332 this.#observers.forEach((observer) => {
333 observer.onMutationUpdate(action)
334 })
335 this.#mutationCache.notify({
336 mutation: this,
337 type: 'updated',
338 action,
339 })
340 })
341 }
342}
343β
344export function getDefaultState<
345 TData,
346 TError,
347 TVariables,
348 TContext,
349>(): MutationState<TData, TError, TVariables, TContext> {
350 return {
351 context: undefined,
352 data: undefined,
353 error: null,
354 failureCount: 0,
355 failureReason: null,
356 isPaused: false,
357 status: 'idle',
358 variables: undefined,
359 submittedAt: 0,
360 }
361}