Open History to see the last commit
1import type { MutationOptions, MutationStatus, MutationMeta } from './types'
2import type { MutationCache } from './mutationCache'
3import type { MutationObserver } from './mutationObserver'
4import type { Logger } from './logger'
5import { defaultLogger } from './logger'
6import { notifyManager } from './notifyManager'
7import { Removable } from './removable'
8import type { Retryer } from './retryer'
9import { canFetch, createRetryer } 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
21}
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
37}
38β
39interface FailedAction<TError> {
40 type: 'failed'
41 failureCount: number
42 error: TError | null
43}
44β
45interface LoadingAction<TVariables, TContext> {
46 type: 'loading'
47 variables?: TVariables
48 context?: TContext
49}
50β
51interface SuccessAction<TData> {
52 type: 'success'
53 data: TData
54}
55β
56interface ErrorAction<TError> {
57 type: 'error'
58 error: TError
59}
60β
61interface PauseAction {
62 type: 'pause'
63}
64β
65interface ContinueAction {
66 type: 'continue'
67}
68β
69interface SetStateAction<TData, TError, TVariables, TContext> {
70 type: 'setState'
71 state: MutationState<TData, TError, TVariables, TContext>
72}
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 meta: MutationMeta | undefined
95β
96 private observers: MutationObserver<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.options = {
105 ...config.defaultOptions,
106 ...config.options,
107 }
108 this.mutationId = config.mutationId
109 this.mutationCache = config.mutationCache
110 this.logger = config.logger || defaultLogger
111 this.observers = []
112 this.state = config.state || getDefaultState()
113 this.meta = config.meta
114β
115 this.updateCacheTime(this.options.cacheTime)
116 this.scheduleGc()
117 }
118β
119 setState(state: MutationState<TData, TError, TVariables, TContext>): void {
120 this.dispatch({ type: 'setState', state })
121 }
122β
123 addObserver(observer: MutationObserver<any, any, any, any>): void {
124 if (this.observers.indexOf(observer) === -1) {
125 this.observers.push(observer)
126β
127 // Stop the mutation from being garbage collected
128 this.clearGcTimeout()
129β
130 this.mutationCache.notify({
131 type: 'observerAdded',
132 mutation: this,
133 observer,
134 })
135 }
136 }
137β
138 removeObserver(observer: MutationObserver<any, any, any, any>): void {
139 this.observers = this.observers.filter((x) => x !== observer)
140β
141 this.scheduleGc()
142β
143 this.mutationCache.notify({
144 type: 'observerRemoved',
145 mutation: this,
146 observer,
147 })
148 }
149β
150 protected optionalRemove() {
151 if (!this.observers.length) {
152 if (this.state.status === 'loading') {
153 this.scheduleGc()
154 } else {
155 this.mutationCache.remove(this)
156 }
157 }
158 }
159β
160 continue(): Promise<TData> {
161 if (this.retryer) {
162 this.retryer.continue()
163 return this.retryer.promise
164 }
165 return this.execute()
166 }
167β
168 async execute(): Promise<TData> {
169 const executeMutation = () => {
170 this.retryer = createRetryer({
171 fn: () => {
172 if (!this.options.mutationFn) {
173 return Promise.reject('No mutationFn found')
174 }
175 return this.options.mutationFn(this.state.variables!)
176 },
177 onFail: (failureCount, error) => {
178 this.dispatch({ type: 'failed', failureCount, error })
179 },
180 onPause: () => {
181 this.dispatch({ type: 'pause' })
182 },
183 onContinue: () => {
184 this.dispatch({ type: 'continue' })
185 },
186 retry: this.options.retry ?? 0,
187 retryDelay: this.options.retryDelay,
188 networkMode: this.options.networkMode,
189 })
190β
191 return this.retryer.promise
192 }
193β
194 const restored = this.state.status === 'loading'
195 try {
196 if (!restored) {
197 this.dispatch({ type: 'loading', variables: this.options.variables! })
198 // Notify cache callback
199 await this.mutationCache.config.onMutate?.(
200 this.state.variables,
201 this as Mutation<unknown, unknown, unknown, unknown>,
202 )
203 const context = await this.options.onMutate?.(this.state.variables!)
204 if (context !== this.state.context) {
205 this.dispatch({
206 type: 'loading',
207 context,
208 variables: this.state.variables,
209 })
210 }
211 }
212 const data = await executeMutation()
213β
214 // Notify cache callback
215 await this.mutationCache.config.onSuccess?.(
216 data,
217 this.state.variables,
218 this.state.context,
219 this as Mutation<unknown, unknown, unknown, unknown>,
220 )
221β
222 await this.options.onSuccess?.(
223 data,
224 this.state.variables!,
225 this.state.context!,
226 )
227β
228 await this.options.onSettled?.(
229 data,
230 null,
231 this.state.variables!,
232 this.state.context,
233 )
234β
235 this.dispatch({ type: 'success', data })
236 return data
237 } catch (error) {
238 try {
239 // Notify cache callback
240 await this.mutationCache.config.onError?.(
241 error,
242 this.state.variables,
243 this.state.context,
244 this as Mutation<unknown, unknown, unknown, unknown>,
245 )
246β
247 if (process.env.NODE_ENV !== 'production') {
248 this.logger.error(error)
249 }
250β
251 await this.options.onError?.(
252 error as TError,
253 this.state.variables!,
254 this.state.context,
255 )
256β
257 await this.options.onSettled?.(
258 undefined,
259 error as TError,
260 this.state.variables!,
261 this.state.context,
262 )
263 throw error
264 } finally {
265 this.dispatch({ type: 'error', error: error as TError })
266 }
267 }
268 }
269β
270 private dispatch(action: Action<TData, TError, TVariables, TContext>): void {
271 const reducer = (
272 state: MutationState<TData, TError, TVariables, TContext>,
273 ): MutationState<TData, TError, TVariables, TContext> => {
274 switch (action.type) {
275 case 'failed':
276 return {
277 ...state,
278 failureCount: action.failureCount,
279 failureReason: action.error,
280 }
281 case 'pause':
282 return {
283 ...state,
284 isPaused: true,
285 }
286 case 'continue':
287 return {
288 ...state,
289 isPaused: false,
290 }
291 case 'loading':
292 return {
293 ...state,
294 context: action.context,
295 data: undefined,
296 failureCount: 0,
297 failureReason: null,
298 error: null,
299 isPaused: !canFetch(this.options.networkMode),
300 status: 'loading',
301 variables: action.variables,
302 }
303 case 'success':
304 return {
305 ...state,
306 data: action.data,
307 failureCount: 0,
308 failureReason: null,
309 error: null,
310 status: 'success',
311 isPaused: false,
312 }
313 case 'error':
314 return {
315 ...state,
316 data: undefined,
317 error: action.error,
318 failureCount: state.failureCount + 1,
319 failureReason: action.error,
320 isPaused: false,
321 status: 'error',
322 }
323 case 'setState':
324 return {
325 ...state,
326 ...action.state,
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 }
343}
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 }
361}