Open History to see the last commit
1import { notifyManager } from './notifyManager'
2import { Mutation } from './mutation'
3import { matchMutation, noop } from './utils'
4import { Subscribable } from './subscribable'
5import type { MutationObserver } from './mutationObserver'
6import type {
7 DefaultError,
8 MutationFunctionContext,
9 MutationOptions,
10 NotifyEvent,
11} from './types'
12import type { QueryClient } from './queryClient'
13import type { Action, MutationState } from './mutation'
14import type { MutationFilters } from './utils'
15β
16// TYPES
17β
18/**
19 * Global callbacks that fire for every mutation handled by a `MutationCache`, regardless of which
20 * component or observer triggered it. They differ from the `defaultOptions` provided to a
21 * `QueryClient` in two ways: `defaultOptions` can be overridden by each mutation, while these
22 * callbacks are always called, and `onMutate` here does not allow returning a result.
23 *
24 * If a callback returns a promise, it will be awaited before the mutation continues.
25 */
26export interface MutationCacheConfig {
27 /** Called when any mutation in the cache encounters an error. */
28 onError?: (
29 error: DefaultError,
30 variables: unknown,
31 onMutateResult: unknown,
32 mutation: Mutation<unknown, unknown, unknown>,
33 context: MutationFunctionContext,
34 ) => Promise<unknown> | unknown
35 /** Called when any mutation in the cache is successful. */
36 onSuccess?: (
37 data: unknown,
38 variables: unknown,
39 onMutateResult: unknown,
40 mutation: Mutation<unknown, unknown, unknown>,
41 context: MutationFunctionContext,
42 ) => Promise<unknown> | unknown
43 /** Called before any mutation in the cache executes. */
44 onMutate?: (
45 variables: unknown,
46 mutation: Mutation<unknown, unknown, unknown>,
47 context: MutationFunctionContext,
48 ) => Promise<unknown> | unknown
49 /** Called when any mutation in the cache is settled, either successfully or with an error. */
50 onSettled?: (
51 data: unknown | undefined,
52 error: DefaultError | null,
53 variables: unknown,
54 onMutateResult: unknown,
55 mutation: Mutation<unknown, unknown, unknown>,
56 context: MutationFunctionContext,
57 ) => Promise<unknown> | unknown
58}
59β
60interface NotifyEventMutationAdded extends NotifyEvent {
61 type: 'added'
62 mutation: Mutation<any, any, any, any>
63}
64interface NotifyEventMutationRemoved extends NotifyEvent {
65 type: 'removed'
66 mutation: Mutation<any, any, any, any>
67}
68β
69interface NotifyEventMutationObserverAdded extends NotifyEvent {
70 type: 'observerAdded'
71 mutation: Mutation<any, any, any, any>
72 observer: MutationObserver<any, any, any>
73}
74β
75interface NotifyEventMutationObserverRemoved extends NotifyEvent {
76 type: 'observerRemoved'
77 mutation: Mutation<any, any, any, any>
78 observer: MutationObserver<any, any, any>
79}
80β
81interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {
82 type: 'observerOptionsUpdated'
83 mutation?: Mutation<any, any, any, any>
84 observer: MutationObserver<any, any, any, any>
85}
86β
87interface NotifyEventMutationUpdated extends NotifyEvent {
88 type: 'updated'
89 mutation: Mutation<any, any, any, any>
90 action: Action<any, any, any, any>
91}
92β
93/**
94 * The event passed to a `MutationCache` subscriber. Fired whenever a mutation is added or removed
95 * from the cache, its state is updated, or one of its observers is added, removed, or has its
96 * options updated.
97 */
98export type MutationCacheNotifyEvent =
99 | NotifyEventMutationAdded
100 | NotifyEventMutationRemoved
101 | NotifyEventMutationObserverAdded
102 | NotifyEventMutationObserverRemoved
103 | NotifyEventMutationObserverOptionsUpdated
104 | NotifyEventMutationUpdated
105β
106type MutationCacheListener = (event: MutationCacheNotifyEvent) => void
107β
108// CLASS
109β
110/**
111 * The `MutationCache` is the storage for mutations.
112 *
113 * Normally, you will not interact with the `MutationCache` directly and instead use a
114 * `QueryClient`. You can subscribe to it (inherited from `Subscribable`) to be informed of
115 * safe/known updates to the cache, such as mutations being added, removed, or updated.
116 * @example
117 * ```ts
118 * const unsubscribe = mutationCache.subscribe((event) => {
119 * console.log(event.type, event.mutation)
120 * })
121 * ```
122 */
123export class MutationCache extends Subscribable<MutationCacheListener> {
124 #mutations: Set<Mutation<any, any, any, any>>
125 #scopes: Map<string, Array<Mutation<any, any, any, any>>>
126 #mutationId: number
127β
128 constructor(public config: MutationCacheConfig = {}) {
129 super()
130 this.#mutations = new Set()
131 this.#scopes = new Map()
132 this.#mutationId = 0
133 }
134β
135 /**
136 * Creates a mutation and adds it to the cache.
137 * @internal
138 * @param client - The client the mutation belongs to, used to default its options.
139 * @param options - The mutation options. They are defaulted with {@link
140 * QueryClient#defaultMutationOptions}.
141 * @param state - The initial state of the mutation, e.g. when restoring a dehydrated mutation.
142 * @returns The new mutation, already added to the cache.
143 */
144 build<TData, TError, TVariables, TOnMutateResult>(
145 client: QueryClient,
146 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
147 state?: MutationState<TData, TError, TVariables, TOnMutateResult>,
148 ): Mutation<TData, TError, TVariables, TOnMutateResult> {
149 const mutation = new Mutation({
150 client,
151 mutationCache: this,
152 mutationId: ++this.#mutationId,
153 options: client.defaultMutationOptions(options),
154 state,
155 })
156β
157 this.add(mutation)
158β
159 return mutation
160 }
161β
162 /**
163 * Adds a mutation to the cache.
164 * @internal
165 * @param mutation - The mutation to add. If it has a `scope`, it is queued in that scope.
166 */
167 add(mutation: Mutation<any, any, any, any>): void {
168 this.#mutations.add(mutation)
169 const scope = scopeFor(mutation)
170 if (typeof scope === 'string') {
171 const scopedMutations = this.#scopes.get(scope)
172 if (scopedMutations) {
173 scopedMutations.push(mutation)
174 } else {
175 this.#scopes.set(scope, [mutation])
176 }
177 }
178 this.notify({ type: 'added', mutation })
179 }
180β
181 /**
182 * Removes a mutation from the cache.
183 * @internal
184 * @param mutation - The mutation to remove, also from its scope's queue.
185 */
186 remove(mutation: Mutation<any, any, any, any>): void {
187 if (this.#mutations.delete(mutation)) {
188 const scope = scopeFor(mutation)
189 if (typeof scope === 'string') {
190 const scopedMutations = this.#scopes.get(scope)
191 if (scopedMutations) {
192 if (scopedMutations.length > 1) {
193 const index = scopedMutations.indexOf(mutation)
194 if (index !== -1) {
195 scopedMutations.splice(index, 1)
196 }
197 } else if (scopedMutations[0] === mutation) {
198 this.#scopes.delete(scope)
199 }
200 }
201 }
202 }
203β
204 // Currently we notify the removal even if the mutation was already removed.
205 // Consider making this an error or not notifying of the removal depending on the desired semantics.
206 this.notify({ type: 'removed', mutation })
207 }
208β
209 /**
210 * Checks whether a mutation can run now, given the other mutations in its `scope`.
211 * @internal
212 * @param mutation - The mutation to check.
213 * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending
214 * ahead of it.
215 */
216 canRun(mutation: Mutation<any, any, any, any>): boolean {
217 const scope = scopeFor(mutation)
218 if (typeof scope === 'string') {
219 const mutationsWithSameScope = this.#scopes.get(scope)
220 const firstPendingMutation = mutationsWithSameScope?.find(
221 (m) => m.state.status === 'pending',
222 )
223 // we can run if there is no current pending mutation (start use-case)
224 // or if WE are the first pending mutation (continue use-case)
225 return !firstPendingMutation || firstPendingMutation === mutation
226 } else {
227 // For unscoped mutations there are never any pending mutations in front of the
228 // current mutation
229 return true
230 }
231 }
232β
233 /**
234 * Continues the next paused mutation in the same `scope` after a mutation finishes.
235 * @internal
236 * @param mutation - The mutation that finished.
237 * @returns A promise that resolves once the next paused mutation in the same scope has continued,
238 * or immediately if there is none.
239 */
240 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
241 const scope = scopeFor(mutation)
242 if (typeof scope === 'string') {
243 const foundMutation = this.#scopes
244 .get(scope)
245 ?.find((m) => m !== mutation && m.state.isPaused)
246β
247 return foundMutation?.continue() ?? Promise.resolve()
248 } else {
249 return Promise.resolve()
250 }
251 }
252β
253 /**
254 * Removes all mutations from the cache.
255 * @example
256 * ```ts
257 * const mutationCache = queryClient.getMutationCache()
258 *
259 * mutationCache.clear()
260 * ```
261 */
262 clear(): void {
263 notifyManager.batch(() => {
264 const mutations = this.getAll()
265 this.#mutations.clear()
266 this.#scopes.clear()
267 mutations.forEach((mutation) => {
268 this.notify({ type: 'removed', mutation })
269 })
270 })
271 }
272β
273 /**
274 * Returns all mutations within the cache.
275 *
276 * This is not typically needed for most applications, but can come in handy when needing more
277 * information about a mutation in rare scenarios.
278 * @returns Every mutation in the cache.
279 * @example
280 * ```ts
281 * const mutationCache = queryClient.getMutationCache()
282 *
283 * const mutations = mutationCache.getAll()
284 * ```
285 */
286 getAll(): Array<Mutation> {
287 return Array.from(this.#mutations)
288 }
289β
290 /**
291 * A slightly more advanced method that can be used to get an existing mutation instance from
292 * the cache. If the mutation does not exist, `undefined` is returned.
293 *
294 * This is not typically needed for most applications, but can come in handy when needing more
295 * information about a mutation in rare scenarios.
296 * @param filters - The filters to match. `exact` defaults to `true`.
297 * @returns The first matching mutation, or `undefined`.
298 * @see {@link MutationCache#findAll}
299 * @example
300 * ```ts
301 * const mutationCache = queryClient.getMutationCache()
302 *
303 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
304 * ```
305 */
306 find<
307 TData = unknown,
308 TError = DefaultError,
309 TVariables = any,
310 TOnMutateResult = unknown,
311 >(
312 filters: MutationFilters,
313 ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {
314 const defaultedFilters = { exact: true, ...filters }
315β
316 return this.getAll().find((mutation) =>
317 matchMutation(defaultedFilters, mutation),
318 ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
319 }
320β
321 /**
322 * An even more advanced method that can be used to get existing mutation instances from the
323 * cache that match the given filters. If no mutations match, an empty array is returned.
324 *
325 * This is not typically needed for most applications, but can come in handy when needing more
326 * information about mutations in rare scenarios.
327 * @param filters - The filters to match. Without filters, every mutation is returned.
328 * @returns The matching mutations.
329 * @see {@link MutationCache#find}
330 * @example
331 * ```ts
332 * const mutationCache = queryClient.getMutationCache()
333 *
334 * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
335 * ```
336 */
337 findAll(filters: MutationFilters = {}): Array<Mutation> {
338 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
339 }
340β
341 /**
342 * Notifies every cache listener of an event, in one batch.
343 * @internal
344 * @param event - The event passed to every listener.
345 */
346 notify(event: MutationCacheNotifyEvent) {
347 notifyManager.batch(() => {
348 this.listeners.forEach((listener) => {
349 listener(event)
350 })
351 })
352 }
353β
354 /**
355 * Continues every paused mutation, e.g. when the app comes back online.
356 * @internal
357 * @returns A promise that resolves once every paused mutation has continued and settled.
358 */
359 resumePausedMutations(): Promise<unknown> {
360 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
361β
362 return notifyManager.batch(() =>
363 Promise.all(
364 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
365 ),
366 )
367 }
368}
369β
370/**
371 * Returns the scope id of a mutation, used to run mutations with the same scope one after another.
372 * @param mutation - The mutation to read the scope of.
373 * @returns The mutation's `scope.id`, or `undefined` if it has no scope.
374 */
375function scopeFor(mutation: Mutation<any, any, any, any>) {
376 return mutation.options.scope?.id
377}