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

mutationCache.ts

386 lines12.7 KB

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