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