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

mutationCache.ts

390 lines12.8 KB

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
59​
60interface NotifyEventMutationAdded extends NotifyEvent {
61 type: 'added'
62 mutation: Mutation<any, any, any, any>
64interface NotifyEventMutationRemoved extends NotifyEvent {
65 type: 'removed'
66 mutation: Mutation<any, any, any, any>
68​
69interface NotifyEventMutationObserverAdded extends NotifyEvent {
70 type: 'observerAdded'
71 mutation: Mutation<any, any, any, any>
72 observer: MutationObserver<any, any, any>
74​
75interface NotifyEventMutationObserverRemoved extends NotifyEvent {
76 type: 'observerRemoved'
77 mutation: Mutation<any, any, any, any>
78 observer: MutationObserver<any, any, any>
80​
81interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {
82 type: 'observerOptionsUpdated'
83 mutation?: Mutation<any, any, any, any>
84 observer: MutationObserver<any, any, any, any>
86​
87interface NotifyEventMutationUpdated extends NotifyEvent {
88 type: 'updated'
89 mutation: Mutation<any, any, any, any>
90 action: Action<any, any, any, any>
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 and clears its garbage collection timer.
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 this cache still holds the given mutation.
212 * @internal
213 * @param mutation - The mutation to check.
214 * @returns Whether the mutation is in the cache.
215 */
216 has(mutation: Mutation<any, any, any, any>): boolean {
217 return this.#mutations.has(mutation)
218 }
219​
220 /**
221 * Checks whether a mutation can run now, given the other mutations in its `scope`.
222 * @internal
223 * @param mutation - The mutation to check.
224 * @returns `true` if the mutation has no `scope`, or no other mutation in its scope is pending
225 * ahead of it.
226 */
227 canRun(mutation: Mutation<any, any, any, any>): boolean {
228 const scope = scopeFor(mutation)
229 if (typeof scope === 'string') {
230 const mutationsWithSameScope = this.#scopes.get(scope)
231 const firstPendingMutation = mutationsWithSameScope?.find(
232 (m) => m.state.status === 'pending',
233 )
234 // we can run if there is no current pending mutation (start use-case)
235 // or if WE are the first pending mutation (continue use-case)
236 return !firstPendingMutation || firstPendingMutation === mutation
237 } else {
238 // For unscoped mutations there are never any pending mutations in front of the
239 // current mutation
240 return true
241 }
242 }
243​
244 /**
245 * Continues the next paused mutation in the same `scope` after a mutation finishes.
246 * @internal
247 * @param mutation - The mutation that finished.
248 * @returns A promise that resolves once the next paused mutation in the same scope has continued,
249 * or immediately if there is none.
250 */
251 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
252 const scope = scopeFor(mutation)
253 if (typeof scope === 'string') {
254 const foundMutation = this.#scopes
255 .get(scope)
256 ?.find((m) => m !== mutation && m.state.isPaused)
257​
258 return foundMutation?.continue() ?? Promise.resolve()
259 } else {
260 return Promise.resolve()
261 }
262 }
263​
264 /**
265 * Removes all mutations and clears their garbage collection timers.
266 * Mutations that are already running continue to execute.
267 * @example
268 * ```ts
269 * const mutationCache = queryClient.getMutationCache()
270 *
271 * mutationCache.clear()
272 * ```
273 */
274 clear(): void {
275 notifyManager.batch(() => {
276 const mutations = this.getAll()
277 this.#mutations.clear()
278 this.#scopes.clear()
279 mutations.forEach((mutation) => mutation.destroy())
280 mutations.forEach((mutation) => {
281 this.notify({ type: 'removed', mutation })
282 })
283 })
284 }
285​
286 /**
287 * Returns all mutations within the cache.
288 *
289 * This is not typically needed for most applications, but can come in handy when needing more
290 * information about a mutation in rare scenarios.
291 * @returns Every mutation in the cache.
292 * @example
293 * ```ts
294 * const mutationCache = queryClient.getMutationCache()
295 *
296 * const mutations = mutationCache.getAll()
297 * ```
298 */
299 getAll(): Array<Mutation> {
300 return Array.from(this.#mutations)
301 }
302​
303 /**
304 * A slightly more advanced method that can be used to get an existing mutation instance from
305 * the cache. If the mutation does not exist, `undefined` is returned.
306 *
307 * This is not typically needed for most applications, but can come in handy when needing more
308 * information about a mutation in rare scenarios.
309 * @param filters - The filters to match. `exact` defaults to `true`.
310 * @returns The first matching mutation, or `undefined`.
311 * @see {@link MutationCache#findAll}
312 * @example
313 * ```ts
314 * const mutationCache = queryClient.getMutationCache()
315 *
316 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
317 * ```
318 */
319 find<
320 TData = unknown,
321 TError = DefaultError,
322 TVariables = any,
323 TOnMutateResult = unknown,
324 >(
325 filters: MutationFilters,
326 ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {
327 const defaultedFilters = { exact: true, ...filters }
328​
329 return this.getAll().find((mutation) =>
330 matchMutation(defaultedFilters, mutation),
331 ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
332 }
333​
334 /**
335 * An even more advanced method that can be used to get existing mutation instances from the
336 * cache that match the given filters. If no mutations match, an empty array is returned.
337 *
338 * This is not typically needed for most applications, but can come in handy when needing more
339 * information about mutations in rare scenarios.
340 * @param filters - The filters to match. Without filters, every mutation is returned.
341 * @returns The matching mutations.
342 * @see {@link MutationCache#find}
343 * @example
344 * ```ts
345 * const mutationCache = queryClient.getMutationCache()
346 *
347 * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
348 * ```
349 */
350 findAll(filters: MutationFilters = {}): Array<Mutation> {
351 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
352 }
353​
354 /**
355 * Notifies every cache listener of an event, in one batch.
356 * @internal
357 * @param event - The event passed to every listener.
358 */
359 notify(event: MutationCacheNotifyEvent) {
360 notifyManager.batch(() => {
361 this.listeners.forEach((listener) => {
362 listener(event)
363 })
364 })
365 }
366​
367 /**
368 * Continues every paused mutation, e.g. when the app comes back online.
369 * @internal
370 * @returns A promise that resolves once every paused mutation has continued and settled.
371 */
372 resumePausedMutations(): Promise<unknown> {
373 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
374​
375 return notifyManager.batch(() =>
376 Promise.all(
377 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
378 ),
379 )
380 }
382​
383/**
384 * Returns the scope id of a mutation, used to run mutations with the same scope one after another.
385 * @param mutation - The mutation to read the scope of.
386 * @returns The mutation's `scope.id`, or `undefined` if it has no scope.
387 */
388function scopeFor(mutation: Mutation<any, any, any, any>) {
389 return mutation.options.scope?.id