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β
95 private observers: MutationObserver<TData, TError, TVariables, TContext>[]
96 private mutationCache: MutationCache
97 private logger: Logger
98 private retryer?: Retryer<TData>
99β
100 constructor(config: MutationConfig<TData, TError, TVariables, TContext>) {
101 super()
102β
103 this.options = {
104 ...config.defaultOptions,
105 ...config.options,
106 }
107 this.mutationId = config.mutationId
108 this.mutationCache = config.mutationCache
109 this.logger = config.logger || defaultLogger
110 this.observers = []
111 this.state = config.state || getDefaultState()
112β
113 this.updateCacheTime(this.options.cacheTime)
114 this.scheduleGc()
115 }
116β
117 get meta(): MutationMeta | undefined {
118 return this.options.meta
119 }
120β
121 setState(state: MutationState<TData, TError, TVariables, TContext>): void {
122 this.dispatch({ type: 'setState', state })
123 }
124β
125 addObserver(observer: MutationObserver<any, any, any, any>): void {
126 if (this.observers.indexOf(observer) === -1) {
127 this.observers.push(observer)
128β
129 // Stop the mutation from being garbage collected
130 this.clearGcTimeout()
131β
132 this.mutationCache.notify({
133 type: 'observerAdded',
134 mutation: this,
135 observer,
136 })
137 }
138 }
139β
140 removeObserver(observer: MutationObserver<any, any, any, any>): void {
141 this.observers = this.observers.filter((x) => x !== observer)
142β
143 this.scheduleGc()
144β
145 this.mutationCache.notify({
146 type: 'observerRemoved',
147 mutation: this,
148 observer,
149 })
150 }
151β
152 protected optionalRemove() {
153 if (!this.observers.length) {
154 if (this.state.status === 'loading') {
155 this.scheduleGc()
156 } else {
157 this.mutationCache.remove(this)
158 }
159 }
160 }
161β
162 continue(): Promise<unknown> {
163 return this.retryer?.continue() ?? this.execute()
164 }
165β
166 async execute(): Promise<TData> {
167 const executeMutation = () => {
168 this.retryer = createRetryer({
169 fn: () => {
170 if (!this.options.mutationFn) {
171 return Promise.reject('No mutationFn found')
172 }
173 return this.options.mutationFn(this.state.variables!)
174 },
175 onFail: (failureCount, error) => {
176 this.dispatch({ type: 'failed', failureCount, error })
177 },
178 onPause: () => {
179 this.dispatch({ type: 'pause' })
180 },
181 onContinue: () => {
182 this.dispatch({ type: 'continue' })
183 },
184 retry: this.options.retry ?? 0,
185 retryDelay: this.options.retryDelay,
186 networkMode: this.options.networkMode,
187 })
188β
189 return this.retryer.promise
190 }
191β
192 const restored = this.state.status === 'loading'
193 try {
194 if (!restored) {
195 this.dispatch({ type: 'loading', variables: this.options.variables! })
196 // Notify cache callback
197 await this.mutationCache.config.onMutate?.(
198 this.state.variables,
199 this as Mutation<unknown, unknown, unknown, unknown>,
200 )
201 const context = await this.options.onMutate?.(this.state.variables!)
202 if (context !== this.state.context) {
203 this.dispatch({
204 type: 'loading',
205 context,
206 variables: this.state.variables,
207 })
208 }
209 }
210 const data = await executeMutation()
211β
212 // Notify cache callback
213 await this.mutationCache.config.onSuccess?.(
214 data,
215 this.state.variables,
216 this.state.context,
217 this as Mutation<unknown, unknown, unknown, unknown>,
218 )
219β
220 await this.options.onSuccess?.(
221 data,
222 this.state.variables!,
223 this.state.context!,
224 )
225β
226 await this.options.onSettled?.(
227 data,
228 null,
229 this.state.variables!,
230 this.state.context,
231 )
232β
233 this.dispatch({ type: 'success', data })
234 return data
235 } catch (error) {
236 try {
237 // Notify cache callback
238 await this.mutationCache.config.onError?.(
239 error,
240 this.state.variables,
241 this.state.context,
242 this as Mutation<unknown, unknown, unknown, unknown>,
243 )
244β
245 if (process.env.NODE_ENV !== 'production') {
246 this.logger.error(error)
247 }
248β
249 await this.options.onError?.(
250 error as TError,
251 this.state.variables!,
252 this.state.context,
253 )
254β
255 await this.options.onSettled?.(
256 undefined,
257 error as TError,
258 this.state.variables!,
259 this.state.context,
260 )
261 throw error
262 } finally {
263 this.dispatch({ type: 'error', error: error as TError })
264 }
265 }
266 }
267β
268 private dispatch(action: Action<TData, TError, TVariables, TContext>): void {
269 const reducer = (
270 state: MutationState<TData, TError, TVariables, TContext>,
271 ): MutationState<TData, TError, TVariables, TContext> => {
272 switch (action.type) {
273 case 'failed':
274 return {
275 ...state,
276 failureCount: action.failureCount,
277 failureReason: action.error,
278 }
279 case 'pause':
280 return {
281 ...state,
282 isPaused: true,
283 }
284 case 'continue':
285 return {
286 ...state,
287 isPaused: false,
288 }
289 case 'loading':
290 return {
291 ...state,
292 context: action.context,
293 data: undefined,
294 failureCount: 0,
295 failureReason: null,
296 error: null,
297 isPaused: !canFetch(this.options.networkMode),
298 status: 'loading',
299 variables: action.variables,
300 }
301 case 'success':
302 return {
303 ...state,
304 data: action.data,
305 failureCount: 0,
306 failureReason: null,
307 error: null,
308 status: 'success',
309 isPaused: false,
310 }
311 case 'error':
312 return {
313 ...state,
314 data: undefined,
315 error: action.error,
316 failureCount: state.failureCount + 1,
317 failureReason: action.error,
318 isPaused: false,
319 status: 'error',
320 }
321 case 'setState':
322 return {
323 ...state,
324 ...action.state,
325 }
326 }
327 }
328 this.state = reducer(this.state)
329β
330 notifyManager.batch(() => {
331 this.observers.forEach((observer) => {
332 observer.onMutationUpdate(action)
333 })
334 this.mutationCache.notify({
335 mutation: this,
336 type: 'updated',
337 action,
338 })
339 })
340 }
341}
342β
343export function getDefaultState<
344 TData,
345 TError,
346 TVariables,
347 TContext,
348>(): MutationState<TData, TError, TVariables, TContext> {
349 return {
350 context: undefined,
351 data: undefined,
352 error: null,
353 failureCount: 0,
354 failureReason: null,
355 isPaused: false,
356 status: 'idle',
357 variables: undefined,
358 }
359}