Open History to see the last commit
1import type { MutationOptions } from './types'
2import type { QueryClient } from './queryClient'
3import { notifyManager } from './notifyManager'
4import { Mutation, MutationState } from './mutation'
5import { noop } from './utils'
6import { Subscribable } from './subscribable'
7β
8// TYPES
9β
10interface MutationCacheConfig {
11 onError?: (
12 error: unknown,
13 variables: unknown,
14 context: unknown,
15 mutation: Mutation<unknown, unknown, unknown, unknown>
16 ) => void
17}
18β
19type MutationCacheListener = (mutation?: Mutation) => void
20β
21// CLASS
22β
23export class MutationCache extends Subscribable<MutationCacheListener> {
24 config: MutationCacheConfig
25β
26 private mutations: Mutation<any, any, any, any>[]
27 private mutationId: number
28β
29 constructor(config?: MutationCacheConfig) {
30 super()
31 this.config = config || {}
32 this.mutations = []
33 this.mutationId = 0
34 }
35β
36 build<TData, TError, TVariables, TContext>(
37 client: QueryClient,
38 options: MutationOptions<TData, TError, TVariables, TContext>,
39 state?: MutationState<TData, TError, TVariables, TContext>
40 ): Mutation<TData, TError, TVariables, TContext> {
41 const mutation = new Mutation({
42 mutationCache: this,
43 mutationId: ++this.mutationId,
44 options: client.defaultMutationOptions(options),
45 state,
46 defaultOptions: options.mutationKey
47 ? client.getMutationDefaults(options.mutationKey)
48 : undefined,
49 })
50β
51 this.add(mutation)
52β
53 return mutation
54 }
55β
56 add(mutation: Mutation<any, any, any, any>): void {
57 this.mutations.push(mutation)
58 this.notify(mutation)
59 }
60β
61 remove(mutation: Mutation<any, any, any, any>): void {
62 this.mutations = this.mutations.filter(x => x !== mutation)
63 mutation.cancel()
64 this.notify(mutation)
65 }
66β
67 clear(): void {
68 notifyManager.batch(() => {
69 this.mutations.forEach(mutation => {
70 this.remove(mutation)
71 })
72 })
73 }
74β
75 getAll(): Mutation[] {
76 return this.mutations
77 }
78β
79 notify(mutation?: Mutation<any, any, any, any>) {
80 notifyManager.batch(() => {
81 this.listeners.forEach(listener => {
82 listener(mutation)
83 })
84 })
85 }
86β
87 onFocus(): void {
88 this.resumePausedMutations()
89 }
90β
91 onOnline(): void {
92 this.resumePausedMutations()
93 }
94β
95 resumePausedMutations(): Promise<void> {
96 const pausedMutations = this.mutations.filter(x => x.state.isPaused)
97 return notifyManager.batch(() =>
98 pausedMutations.reduce(
99 (promise, mutation) =>
100 promise.then(() => mutation.continue().catch(noop)),
101 Promise.resolve()
102 )
103 )
104 }
105}