Open History to see the last commit
1import { Mutation } from './mutation'
2import { notifyManager } from './notifyManager'
3import { Subscribable } from './subscribable'
4import { matchMutation, noop } from './utils'
5import type { Action, MutationState } from './mutation'
6import type { MutationObserver } from './mutationObserver'
7import type { QueryClient } from './queryClient'
8import type {
9 DefaultError,
10 MutationFunctionContext,
11 MutationOptions,
12 NotifyEvent,
13} from './types'
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 mutation.destroy()
189 const scope = scopeFor(mutation)
190 if (typeof scope === 'string') {
191 const scopedMutations = this.#scopes.get(scope)
192 if (scopedMutations) {
193 if (scopedMutations.length > 1) {
194 const index = scopedMutations.indexOf(mutation)
195 if (index !== -1) {
196 scopedMutations.splice(index, 1)
197 }
198 } else if (scopedMutations[0] === mutation) {
199 this.#scopes.delete(scope)
200 }
201 }
202 }
203 }
204β
205 // Currently we notify the removal even if the mutation was already removed.
206 // Consider making this an error or not notifying of the removal depending on the desired semantics.
207 this.notify({ type: 'removed', mutation })
208 }
209β
210 /**
211 * Checks whether a mutation can run now, given the other mutations in its `scope`.
212 * @internal
213 * @param mutation - The mutation to check.
214 * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending
215 * ahead of it.
216 */
217 canRun(mutation: Mutation<any, any, any, any>): boolean {
218 const scope = scopeFor(mutation)
219 if (typeof scope === 'string') {
220 const mutationsWithSameScope = this.#scopes.get(scope)
221 const firstPendingMutation = mutationsWithSameScope?.find(
222 (m) => m.state.status === 'pending',
223 )
224 // we can run if there is no current pending mutation (start use-case)
225 // or if WE are the first pending mutation (continue use-case)
226 return !firstPendingMutation || firstPendingMutation === mutation
227 } else {
228 // For unscoped mutations there are never any pending mutations in front of the
229 // current mutation
230 return true
231 }
232 }
233β
234 /**
235 * Continues the next paused mutation in the same `scope` after a mutation finishes.
236 * @internal
237 * @param mutation - The mutation that finished.
238 * @returns A promise that resolves once the next paused mutation in the same scope has continued,
239 * or immediately if there is none.
240 */
241 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
242 const scope = scopeFor(mutation)
243 if (typeof scope === 'string') {
244 const foundMutation = this.#scopes
245 .get(scope)
246 ?.find((m) => m !== mutation && m.state.isPaused)
247β
248 return foundMutation?.continue() ?? Promise.resolve()
249 } else {
250 return Promise.resolve()
251 }
252 }
253β
254 /**
255 * Removes all mutations from the cache.
256 * @example
257 * ```ts
258 * const mutationCache = queryClient.getMutationCache()
259 *
260 * mutationCache.clear()
261 * ```
262 */
263 clear(): void {
264 notifyManager.batch(() => {
265 const mutations = this.getAll()
266 this.#mutations.clear()
267 this.#scopes.clear()
268 mutations.forEach((mutation) => {
269 mutation.destroy()
270 this.notify({ type: 'removed', mutation })
271 })
272 })
273 }
274β
275 /**
276 * Returns all mutations within the cache.
277 *
278 * This is not typically needed for most applications, but can come in handy when needing more
279 * information about a mutation in rare scenarios.
280 * @returns Every mutation in the cache.
281 * @example
282 * ```ts
283 * const mutationCache = queryClient.getMutationCache()
284 *
285 * const mutations = mutationCache.getAll()
286 * ```
287 */
288 getAll(): Array<Mutation> {
289 return Array.from(this.#mutations)
290 }
291β
292 /**
293 * A slightly more advanced method that can be used to get an existing mutation instance from
294 * the cache. If the mutation does not exist, `undefined` is returned.
295 *
296 * This is not typically needed for most applications, but can come in handy when needing more
297 * information about a mutation in rare scenarios.
298 * @param filters - The filters to match. `exact` defaults to `true`.
299 * @returns The first matching mutation, or `undefined`.
300 * @see {@link MutationCache#findAll}
301 * @example
302 * ```ts
303 * const mutationCache = queryClient.getMutationCache()
304 *
305 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
306 * ```
307 */
308 find<
309 TData = unknown,
310 TError = DefaultError,
311 TVariables = any,
312 TOnMutateResult = unknown,
313 >(
314 filters: MutationFilters,
315 ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {
316 const defaultedFilters = { exact: true, ...filters }
317β
318 return this.getAll().find((mutation) =>
319 matchMutation(defaultedFilters, mutation),
320 ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
321 }
322β
323 /**
324 * An even more advanced method that can be used to get existing mutation instances from the
325 * cache that match the given filters. If no mutations match, an empty array is returned.
326 *
327 * This is not typically needed for most applications, but can come in handy when needing more
328 * information about mutations in rare scenarios.
329 * @param filters - The filters to match. Without filters, every mutation is returned.
330 * @returns The matching mutations.
331 * @see {@link MutationCache#find}
332 * @example
333 * ```ts
334 * const mutationCache = queryClient.getMutationCache()
335 *
336 * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
337 * ```
338 */
339 findAll(filters: MutationFilters = {}): Array<Mutation> {
340 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
341 }
342β
343 /**
344 * Notifies every cache listener of an event, in one batch.
345 * @internal
346 * @param event - The event passed to every listener.
347 */
348 notify(event: MutationCacheNotifyEvent) {
349 notifyManager.batch(() => {
350 this.listeners.forEach((listener) => {
351 listener(event)
352 })
353 })
354 }
355β
356 /**
357 * Continues every paused mutation, e.g. when the app comes back online.
358 * @internal
359 * @returns A promise that resolves once every paused mutation has continued and settled.
360 */
361 resumePausedMutations(): Promise<unknown> {
362 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
363β
364 return notifyManager.batch(() =>
365 Promise.all(
366 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
367 ),
368 )
369 }
370}
371β
372/**
373 * Returns the scope id of a mutation, used to run mutations with the same scope one after another.
374 * @param mutation - The mutation to read the scope of.
375 * @returns The mutation's `scope.id`, or `undefined` if it has no scope.
376 */
377function scopeFor(mutation: Mutation<any, any, any, any>) {
378 return mutation.options.scope?.id
379}