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 mutationCache: this,
103 mutationId: ++this.#mutationId,
104 options: client.defaultMutationOptions(options),
105 state,
106 })
107β
108 this.add(mutation)
109β
110 return mutation
111 }
112β
113 add(mutation: Mutation<any, any, any, any>): void {
114 this.#mutations.add(mutation)
115 const scope = scopeFor(mutation)
116 if (typeof scope === 'string') {
117 const scopedMutations = this.#scopes.get(scope)
118 if (scopedMutations) {
119 scopedMutations.push(mutation)
120 } else {
121 this.#scopes.set(scope, [mutation])
122 }
123 }
124 this.notify({ type: 'added', mutation })
125 }
126β
127 remove(mutation: Mutation<any, any, any, any>): void {
128 if (this.#mutations.delete(mutation)) {
129 const scope = scopeFor(mutation)
130 if (typeof scope === 'string') {
131 const scopedMutations = this.#scopes.get(scope)
132 if (scopedMutations) {
133 if (scopedMutations.length > 1) {
134 const index = scopedMutations.indexOf(mutation)
135 if (index !== -1) {
136 scopedMutations.splice(index, 1)
137 }
138 } else if (scopedMutations[0] === mutation) {
139 this.#scopes.delete(scope)
140 }
141 }
142 }
143 }
144β
145 // Currently we notify the removal even if the mutation was already removed.
146 // Consider making this an error or not notifying of the removal depending on the desired semantics.
147 this.notify({ type: 'removed', mutation })
148 }
149β
150 canRun(mutation: Mutation<any, any, any, any>): boolean {
151 const scope = scopeFor(mutation)
152 if (typeof scope === 'string') {
153 const mutationsWithSameScope = this.#scopes.get(scope)
154 const firstPendingMutation = mutationsWithSameScope?.find(
155 (m) => m.state.status === 'pending',
156 )
157 // we can run if there is no current pending mutation (start use-case)
158 // or if WE are the first pending mutation (continue use-case)
159 return !firstPendingMutation || firstPendingMutation === mutation
160 } else {
161 // For unscoped mutations there are never any pending mutations in front of the
162 // current mutation
163 return true
164 }
165 }
166β
167 runNext(mutation: Mutation<any, any, any, any>): Promise<unknown> {
168 const scope = scopeFor(mutation)
169 if (typeof scope === 'string') {
170 const foundMutation = this.#scopes
171 .get(scope)
172 ?.find((m) => m !== mutation && m.state.isPaused)
173β
174 return foundMutation?.continue() ?? Promise.resolve()
175 } else {
176 return Promise.resolve()
177 }
178 }
179β
180 clear(): void {
181 notifyManager.batch(() => {
182 this.#mutations.forEach((mutation) => {
183 this.notify({ type: 'removed', mutation })
184 })
185 this.#mutations.clear()
186 this.#scopes.clear()
187 })
188 }
189β
190 getAll(): Array<Mutation> {
191 return Array.from(this.#mutations)
192 }
193β
194 find<
195 TData = unknown,
196 TError = DefaultError,
197 TVariables = any,
198 TContext = unknown,
199 >(
200 filters: MutationFilters,
201 ): Mutation<TData, TError, TVariables, TContext> | undefined {
202 const defaultedFilters = { exact: true, ...filters }
203β
204 return this.getAll().find((mutation) =>
205 matchMutation(defaultedFilters, mutation),
206 ) as Mutation<TData, TError, TVariables, TContext> | undefined
207 }
208β
209 findAll(filters: MutationFilters = {}): Array<Mutation> {
210 return this.getAll().filter((mutation) => matchMutation(filters, mutation))
211 }
212β
213 notify(event: MutationCacheNotifyEvent) {
214 notifyManager.batch(() => {
215 this.listeners.forEach((listener) => {
216 listener(event)
217 })
218 })
219 }
220β
221 resumePausedMutations(): Promise<unknown> {
222 const pausedMutations = this.getAll().filter((x) => x.state.isPaused)
223β
224 return notifyManager.batch(() =>
225 Promise.all(
226 pausedMutations.map((mutation) => mutation.continue().catch(noop)),
227 ),
228 )
229 }
230}
231β
232function scopeFor(mutation: Mutation<any, any, any, any>) {
233 return mutation.options.scope?.id
234}