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

mutationCache.ts

244 lines7.1 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​
18interface MutationCacheConfig {
19 onError?: (
20 error: DefaultError,
21 variables: unknown,
22 onMutateResult: unknown,
23 mutation: Mutation<unknown, unknown, unknown>,
24 context: MutationFunctionContext,
25 ) => Promise<unknown> | unknown
26 onSuccess?: (
27 data: unknown,
28 variables: unknown,
29 onMutateResult: unknown,
30 mutation: Mutation<unknown, unknown, unknown>,
31 context: MutationFunctionContext,
32 ) => Promise<unknown> | unknown
33 onMutate?: (
34 variables: unknown,
35 mutation: Mutation<unknown, unknown, unknown>,
36 context: MutationFunctionContext,
37 ) => Promise<unknown> | unknown
38 onSettled?: (
39 data: unknown | undefined,
40 error: DefaultError | null,
41 variables: unknown,
42 onMutateResult: unknown,
43 mutation: Mutation<unknown, unknown, unknown>,
44 context: MutationFunctionContext,
45 ) => Promise<unknown> | unknown
47​
48interface NotifyEventMutationAdded extends NotifyEvent {
49 type: 'added'
50 mutation: Mutation<any, any, any, any>
52interface NotifyEventMutationRemoved extends NotifyEvent {
53 type: 'removed'
54 mutation: Mutation<any, any, any, any>
56​
57interface NotifyEventMutationObserverAdded extends NotifyEvent {
58 type: 'observerAdded'
59 mutation: Mutation<any, any, any, any>
60 observer: MutationObserver<any, any, any>
62​
63interface NotifyEventMutationObserverRemoved extends NotifyEvent {
64 type: 'observerRemoved'
65 mutation: Mutation<any, any, any, any>
66 observer: MutationObserver<any, any, any>
68​
69interface NotifyEventMutationObserverOptionsUpdated extends NotifyEvent {
70 type: 'observerOptionsUpdated'
71 mutation?: Mutation<any, any, any, any>
72 observer: MutationObserver<any, any, any, any>
74​
75interface NotifyEventMutationUpdated extends NotifyEvent {
76 type: 'updated'
77 mutation: Mutation<any, any, any, any>
78 action: Action<any, any, any, any>
80​
81export type MutationCacheNotifyEvent =
82 | NotifyEventMutationAdded
83 | NotifyEventMutationRemoved
84 | NotifyEventMutationObserverAdded
85 | NotifyEventMutationObserverRemoved
86 | NotifyEventMutationObserverOptionsUpdated
87 | NotifyEventMutationUpdated
88​
89type MutationCacheListener = (event: MutationCacheNotifyEvent) => void
90​
91// CLASS
92​
93export class MutationCache extends Subscribable<MutationCacheListener> {
94 #mutations: Set<Mutation<any, any, any, any>>
95 #scopes: Map<string, Array<Mutation<any, any, any, any>>>
96 #mutationId: number
97​
98 constructor(public config: MutationCacheConfig = {}) {
99 super()
100 this.#mutations = new Set()
101 this.#scopes = new Map()
102 this.#mutationId = 0
103 }
104​
105 build<TData, TError, TVariables, TOnMutateResult>(
106 client: QueryClient,
107 options: MutationOptions<TData, TError, TVariables, TOnMutateResult>,
108 state?: MutationState<TData, TError, TVariables, TOnMutateResult>,
109 ): Mutation<TData, TError, TVariables, TOnMutateResult> {
110 const mutation = new Mutation({
111 client,
112 mutationCache: this,
113 mutationId: ++this.#mutationId,
114 options: client.defaultMutationOptions(options),
115 state,
116 })
117​
118 this.add(mutation)
119​
120 return mutation
121 }
122​
123 add(mutation: Mutation<any, any, any, any>): void {
124 this.#mutations.add(mutation)
125 const scope = scopeFor(mutation)
126 if (typeof scope === 'string') {
127 const scopedMutations = this.#scopes.get(scope)
128 if (scopedMutations) {
129 scopedMutations.push(mutation)
130 } else {
131 this.#scopes.set(scope, [mutation])
132 }
133 }
134 this.notify({ type: 'added', mutation })
135 }
136​
137 remove(mutation: Mutation<any, any, any, any>): void {
138 if (this.#mutations.delete(mutation)) {
139 const scope = scopeFor(mutation)
140 if (typeof scope === 'string') {
141 const scopedMutations = this.#scopes.get(scope)
142 if (scopedMutations) {
143 if (scopedMutations.length > 1) {
144 const index = scopedMutations.indexOf(mutation)
145 if (index !== -1) {
146 scopedMutations.splice(index, 1)
147 }
148 } else if (scopedMutations[0] === mutation) {
149 this.#scopes.delete(scope)
150 }
151 }
152 }
153 }
154​
155 // Currently we notify the removal even if the mutation was already removed.
156 // Consider making this an error or not notifying of the removal depending on the desired semantics.
157 this.notify({ type: 'removed', mutation })
158 }
159​
160 canRun(mutation: Mutation<any, any, any, any>): boolean {
161 const scope = scopeFor(mutation)
162 if (typeof scope === 'string') {
163 const mutationsWithSameScope = this.#scopes.get(scope)
164 const firstPendingMutation = mutationsWithSameScope?.find(
165 (m) => m.state.status === 'pending',
166 )
167 // we can run if there is no current pending mutation (start use-case)
168 // or if WE are the first pending mutation (continue use-case)
169 return !firstPendingMutation || firstPendingMutation === mutation
170 } else {
171 // For unscoped mutations there are never any pending mutations in front of the
172 // current mutation
173 return true
174 }
175 }
176​
177 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
178 const scope = scopeFor(mutation)
179 if (typeof scope === 'string') {
180 const foundMutation = this.#scopes
181 .get(scope)
182 ?.find((m) => m !== mutation && m.state.isPaused)
183​
184 return foundMutation?.continue() ?? Promise.resolve()
185 } else {
186 return Promise.resolve()
187 }
188 }
189​
190 clear(): void {
191 notifyManager.batch(() => {
192 this.#mutations.forEach((mutation) => {
193 this.notify({ type: 'removed', mutation })
194 })
195 this.#mutations.clear()
196 this.#scopes.clear()
197 })
198 }
199​
200 getAll(): Array<Mutation> {
201 return Array.from(this.#mutations)
202 }
203​
204 find<
205 TData = unknown,
206 TError = DefaultError,
207 TVariables = any,
208 TOnMutateResult = unknown,
209 >(
210 filters: MutationFilters,
211 ): Mutation<TData, TError, TVariables, TOnMutateResult> | undefined {
212 const defaultedFilters = { exact: true, ...filters }
213​
214 return this.getAll().find((mutation) =>
215 matchMutation(defaultedFilters, mutation),
216 ) as Mutation<TData, TError, TVariables, TOnMutateResult> | undefined
217 }
218​
219 findAll(filters: MutationFilters = {}): Array<Mutation> {
220 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
221 }
222​
223 notify(event: MutationCacheNotifyEvent) {
224 notifyManager.batch(() => {
225 this.listeners.forEach((listener) => {
226 listener(event)
227 })
228 })
229 }
230​
231 resumePausedMutations(): Promise<unknown> {
232 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
233​
234 return notifyManager.batch(() =>
235 Promise.all(
236 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
237 ),
238 )
239 }
241​
242function scopeFor(mutation: Mutation<any, any, any, any>) {
243 return mutation.options.scope?.id