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 })
160 .then(() =>
161 this.options.onSuccess?.(
162 data,
163 this.state.variables!,
164 this.state.context!
165 )
166 )
167 .then(() =>
168 this.options.onSettled?.(
169 data,
170 null,
171 this.state.variables!,
172 this.state.context
173 )
174 )
175 .then(() => {
176 this.dispatch({ type: 'success', data })
177 return data
178 })
179 .catch(error => {
180 // Notify cache callback
181 if (this.mutationCache.config.onError) {
182 this.mutationCache.config.onError(
183 error,
184 this.state.variables,
185 this.state.context,
186 this as Mutation<unknown, unknown, unknown, unknown>
187 )
188 }
189β
190 // Log error
191 getLogger().error(error)
192β
193 return Promise.resolve()
194 .then(() =>
195 this.options.onError?.(
196 error,
197 this.state.variables!,
198 this.state.context
199 )
200 )
201 .then(() =>
202 this.options.onSettled?.(
203 undefined,
204 error,
205 this.state.variables!,
206 this.state.context
207 )
208 )
209 .then(() => {
210 this.dispatch({ type: 'error', error })
211 throw error
212 })
213 })
214 }
215β
216 private executeMutation(): Promise<TData> {
217 this.retryer = new Retryer({
218 fn: () => {
219 if (!this.options.mutationFn) {
220 return Promise.reject('No mutationFn found')
221 }
222 return this.options.mutationFn(this.state.variables!)
223 },
224 onFail: () => {
225 this.dispatch({ type: 'failed' })
226 },
227 onPause: () => {
228 this.dispatch({ type: 'pause' })
229 },
230 onContinue: () => {
231 this.dispatch({ type: 'continue' })
232 },
233 retry: this.options.retry ?? 0,
234 retryDelay: this.options.retryDelay,
235 })
236β
237 return this.retryer.promise
238 }
239β
240 private dispatch(action: Action<TData, TError, TVariables, TContext>): void {
241 this.state = reducer(this.state, action)
242β
243 notifyManager.batch(() => {
244 this.observers.forEach(observer => {
245 observer.onMutationUpdate(action)
246 })
247 this.mutationCache.notify(this)
248 })
249 }
250}
251β
252export function getDefaultState<
253 TData,
254 TError,
255 TVariables,
256 TContext
257>(): MutationState<TData, TError, TVariables, TContext> {
258 return {
259 context: undefined,
260 data: undefined,
261 error: null,
262 failureCount: 0,
263 isPaused: false,
264 status: 'idle',
265 variables: undefined,
266 }
267}
268β
269function reducer<TData, TError, TVariables, TContext>(
270 state: MutationState<TData, TError, TVariables, TContext>,
271 action: Action<TData, TError, TVariables, TContext>
272): MutationState<TData, TError, TVariables, TContext> {
273 switch (action.type) {
274 case 'failed':
275 return {
276 ...state,
277 failureCount: state.failureCount + 1,
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 error: null,
295 isPaused: false,
296 status: 'loading',
297 variables: action.variables,
298 }
299 case 'success':
300 return {
301 ...state,
302 data: action.data,
303 error: null,
304 status: 'success',
305 isPaused: false,
306 }
307 case 'error':
308 return {
309 ...state,
310 data: undefined,
311 error: action.error,
312 failureCount: state.failureCount + 1,
313 isPaused: false,
314 status: 'error',
315 }
316 case 'setState':
317 return {
318 ...state,
319 ...action.state,
320 }
321 default:
322 return state
323 }
324}