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

mutationCache.ts

335 lines10.3 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`, 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 *
117 * @example
118 * ```ts
119 * const unsubscribe = mutationCache.subscribe((event) => {
120 * console.log(event.type, event.mutation)
121 * })
122 * ```
123 */
124export class MutationCache extends Subscribable<MutationCacheListener> {
125 #mutations: Set<Mutation<any, any, any, any>>
126 #scopes: Map<string, Array<Mutation<any, any, any, any>>>
127 #mutationId: number
128​
129 constructor(public config: MutationCacheConfig = {}) {
130 super()
131 this.#mutations = new Set()
132 this.#scopes = new Map()
133 this.#mutationId = 0
134 }
135​
136 /** @internal */
137 build<TData, TError, TVariables, TOnMutateResult>(
138 client: QueryClient,
139 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
140 state?: MutationState<TData, TError, TVariables, TOnMutateResult>,
141 ): Mutation<TData, TError, TVariables, TOnMutateResult> {
142 const mutation = new Mutation({
143 client,
144 mutationCache: this,
145 mutationId: ++this.#mutationId,
146 options: client.defaultMutationOptions(options),
147 state,
148 })
149​
150 this.add(mutation)
151​
152 return mutation
153 }
154​
155 /** @internal */
156 add(mutation: Mutation<any, any, any, any>): void {
157 this.#mutations.add(mutation)
158 const scope = scopeFor(mutation)
159 if (typeof scope === 'string') {
160 const scopedMutations = this.#scopes.get(scope)
161 if (scopedMutations) {
162 scopedMutations.push(mutation)
163 } else {
164 this.#scopes.set(scope, [mutation])
165 }
166 }
167 this.notify({ type: 'added', mutation })
168 }
169​
170 /** @internal */
171 remove(mutation: Mutation<any, any, any, any>): void {
172 if (this.#mutations.delete(mutation)) {
173 const scope = scopeFor(mutation)
174 if (typeof scope === 'string') {
175 const scopedMutations = this.#scopes.get(scope)
176 if (scopedMutations) {
177 if (scopedMutations.length > 1) {
178 const index = scopedMutations.indexOf(mutation)
179 if (index !== -1) {
180 scopedMutations.splice(index, 1)
181 }
182 } else if (scopedMutations[0] === mutation) {
183 this.#scopes.delete(scope)
184 }
185 }
186 }
187 }
188​
189 // Currently we notify the removal even if the mutation was already removed.
190 // Consider making this an error or not notifying of the removal depending on the desired semantics.
191 this.notify({ type: 'removed', mutation })
192 }
193​
194 /** @internal */
195 canRun(mutation: Mutation<any, any, any, any>): boolean {
196 const scope = scopeFor(mutation)
197 if (typeof scope === 'string') {
198 const mutationsWithSameScope = this.#scopes.get(scope)
199 const firstPendingMutation = mutationsWithSameScope?.find(
200 (m) => m.state.status === 'pending',
201 )
202 // we can run if there is no current pending mutation (start use-case)
203 // or if WE are the first pending mutation (continue use-case)
204 return !firstPendingMutation || firstPendingMutation === mutation
205 } else {
206 // For unscoped mutations there are never any pending mutations in front of the
207 // current mutation
208 return true
209 }
210 }
211​
212 /** @internal */
213 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
214 const scope = scopeFor(mutation)
215 if (typeof scope === 'string') {
216 const foundMutation = this.#scopes
217 .get(scope)
218 ?.find((m) => m !== mutation && m.state.isPaused)
219​
220 return foundMutation?.continue() ?? Promise.resolve()
221 } else {
222 return Promise.resolve()
223 }
224 }
225​
226 /**
227 * Removes all mutations from the cache.
228 *
229 * @example
230 * ```ts
231 * const mutationCache = queryClient.getMutationCache()
232 *
233 * mutationCache.clear()
234 * ```
235 */
236 clear(): void {
237 notifyManager.batch(() => {
238 this.#mutations.forEach((mutation) => {
239 this.notify({ type: 'removed', mutation })
240 })
241 this.#mutations.clear()
242 this.#scopes.clear()
243 })
244 }
245​
246 /**
247 * Returns all mutations within the cache.
248 *
249 * This is not typically needed for most applications, but can come in handy when needing more
250 * information about a mutation in rare scenarios.
251 *
252 * @example
253 * ```ts
254 * const mutationCache = queryClient.getMutationCache()
255 *
256 * const mutations = mutationCache.getAll()
257 * ```
258 */
259 getAll(): Array<Mutation> {
260 return Array.from(this.#mutations)
261 }
262​
263 /**
264 * A slightly more advanced method that can be used to get an existing mutation instance from
265 * the cache. If the mutation does not exist, `undefined` is returned.
266 *
267 * This is not typically needed for most applications, but can come in handy when needing more
268 * information about a mutation in rare scenarios.
269 *
270 * @see {@link MutationCache#findAll}
271 * @example
272 * ```ts
273 * const mutationCache = queryClient.getMutationCache()
274 *
275 * const mutation = mutationCache.find({ mutationKey: ['addPost'] })
276 * ```
277 */
278 find<
279 TData = unknown,
280 TError = DefaultError,
281 TVariables = any,
282 TOnMutateResult = unknown,
283 >(
284 filters: MutationFilters,
285 ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {
286 const defaultedFilters = { exact: true, ...filters }
287​
288 return this.getAll().find((mutation) =>
289 matchMutation(defaultedFilters, mutation),
290 ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
291 }
292​
293 /**
294 * An even more advanced method that can be used to get existing mutation instances from the
295 * cache that match the given filters. If no mutations match, an empty array is returned.
296 *
297 * This is not typically needed for most applications, but can come in handy when needing more
298 * information about mutations in rare scenarios.
299 *
300 * @see {@link MutationCache#find}
301 * @example
302 * ```ts
303 * const mutationCache = queryClient.getMutationCache()
304 *
305 * const mutations = mutationCache.findAll({ mutationKey: ['addPost'] })
306 * ```
307 */
308 findAll(filters: MutationFilters = {}): Array<Mutation> {
309 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
310 }
311​
312 /** @internal */
313 notify(event: MutationCacheNotifyEvent) {
314 notifyManager.batch(() => {
315 this.listeners.forEach((listener) => {
316 listener(event)
317 })
318 })
319 }
320​
321 /** @internal */
322 resumePausedMutations(): Promise<unknown> {
323 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
324​
325 return notifyManager.batch(() =>
326 Promise.all(
327 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
328 ),
329 )
330 }
332​
333function scopeFor(mutation: Mutation<any, any, any, any>) {
334 return mutation.options.scope?.id