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