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

mutationCache.ts

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