Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

mutation.ts

339 lines8.1 KB

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