forked from posva/pinia-colada
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmutation-store.ts
278 lines (248 loc) · 8.13 KB
/
mutation-store.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
import type { ComponentInternalInstance, EffectScope, ShallowRef } from 'vue'
import type { AsyncStatus, DataState } from './data-state'
import type { EntryNodeKey } from './tree-map'
import { defineStore } from 'pinia'
import { getCurrentScope, shallowReactive, shallowRef } from 'vue'
import { TreeMapNode } from './tree-map'
import type { _EmptyObject } from './utils'
import { isSameArray, stringifyFlatObject, toValueWithArgs } from './utils'
import type {
_ReduceContext,
UseMutationOptions,
} from './use-mutation'
/**
* A mutation entry in the cache.
*/
export interface UseMutationEntry<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
> {
/**
* The state of the mutation. Contains the data, error and status.
*/
state: ShallowRef<DataState<TResult, TError>>
/**
* The async status of the mutation.
*/
asyncStatus: ShallowRef<AsyncStatus>
/**
* When was this data fetched the last time in ms
*/
when: number
/**
* The serialized key associated with this mutation entry.
*/
key: EntryNodeKey[] | undefined
/**
* The variables used to call the mutation.
*/
vars: ShallowRef<TVars | undefined>
options: UseMutationOptions<TResult, TVars, TError, TContext>
pending: symbol | null
/**
* Component `__hmrId` to track wrong usage of `useQuery` and warn the user.
* @internal
*/
__hmr?: {
id?: string
deps?: Set<EffectScope | ComponentInternalInstance>
skip?: boolean
}
}
function createMutationEntry<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
>(
options: UseMutationOptions<TResult, TVars, TError, TContext>,
key: EntryNodeKey[] | undefined,
vars?: TVars,
): UseMutationEntry<TResult, TVars, TError, TContext> {
return {
state: shallowRef<DataState<TResult, TError>>({
status: 'pending',
data: undefined,
error: null,
}),
asyncStatus: shallowRef<AsyncStatus>('idle'),
when: 0,
vars: shallowRef(vars),
key,
options,
pending: null,
}
}
export const useMutationCache = /* @__PURE__ */ defineStore(
'_pc_mutation',
({ action }) => {
// We have two versions of the cache, one that track changes and another that doesn't so the actions can be used
// inside computed properties
const cachesRaw = new TreeMapNode<
UseMutationEntry<unknown, any, unknown, any>
>()
const caches = shallowReactive(cachesRaw)
function ensure<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
>(
options: UseMutationOptions<TResult, TVars, TError, TContext>,
): UseMutationEntry<TResult, TVars, TError, TContext>
function ensure<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
>(
options: UseMutationOptions<TResult, TVars, TError, TContext>,
entry: UseMutationEntry<TResult, TVars, TError, TContext>,
vars: NoInfer<TVars>,
): UseMutationEntry<TResult, TVars, TError, TContext>
function ensure<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
>(
options: UseMutationOptions<TResult, TVars, TError, TContext>,
entry?: UseMutationEntry<TResult, TVars, TError, TContext>,
vars?: NoInfer<TVars>,
): UseMutationEntry<TResult, TVars, TError, TContext> {
const key
= vars && toValueWithArgs(options.key, vars)?.map(stringifyFlatObject)
if (!entry) {
entry = createMutationEntry(options, key)
if (key) {
caches.set(
key,
// @ts-expect-error: function types with generics are incompatible
entry,
)
}
return createMutationEntry(options, key)
}
// reuse the entry when no key is provided
if (key) {
// update key
if (!entry.key) {
entry.key = key
} else if (!isSameArray(entry.key, key)) {
entry = createMutationEntry(
options,
key,
// the type NonNullable<TVars> is not assignable to TVars
vars as TVars,
)
caches.set(
key,
// @ts-expect-error: function types with generics are incompatible
entry,
)
}
}
return entry
}
// this allows use to attach reactive effects to the scope later on
const scope = getCurrentScope()!
// const globalOptions = inject()
const defineMutationMap = new WeakMap<() => unknown, unknown>()
/**
* Ensures a query created with {@link defineMutation} is present in the cache. If it's not, it creates a new one.
* @param fn - function that defines the query
*/
const ensureDefinedMutation = action(<T>(fn: () => T) => {
let defineMutationResult = defineMutationMap.get(fn)
if (!defineMutationResult) {
defineMutationMap.set(fn, defineMutationResult = scope.run(fn))
}
return defineMutationResult
})
async function mutate<
TResult = unknown,
TVars = unknown,
TError = unknown,
TContext extends Record<any, any> = _EmptyObject,
>(
currentEntry: UseMutationEntry<TResult, TVars, TError, TContext>,
vars: NoInfer<TVars>,
): Promise<TResult> {
currentEntry.asyncStatus.value = 'loading'
currentEntry.vars.value = vars
// TODO: AbortSignal that is aborted when the mutation is called again so we can throw in pending
let currentData: TResult | undefined
let currentError: TError | undefined
type OnMutateContext = Parameters<
Required<
UseMutationOptions<TResult, TVars, TError, TContext>
>['onMutate']
>['1']
type OnSuccessContext = Parameters<
Required<
UseMutationOptions<TResult, TVars, TError, TContext>
>['onSuccess']
>['2']
type OnErrorContext = Parameters<
Required<
UseMutationOptions<TResult, TVars, TError, TContext>
>['onError']
>['2']
const { options } = currentEntry
let context: OnMutateContext | OnErrorContext | OnSuccessContext = {}
const currentCall = (currentEntry.pending = Symbol())
try {
// TODO: implement
// let globalOnMutateContext: UseMutationGlobalContext | undefined
// let globalOnMutateContext = await globalOptions.onMutate?.(vars)
const onMutateContext = (await options.onMutate?.(
vars,
context,
// NOTE: the cast makes it easier to write without extra code. It's safe because { ...null, ...undefined } works and TContext must be a Record<any, any>
)) as _ReduceContext<TContext>
// we set the context here so it can be used by other hooks
context = {
// ...globalOnMutateContext!,
...onMutateContext,
// NOTE: needed for onSuccess cast
} satisfies OnSuccessContext
const newData = (currentData = await options.mutation(
vars,
context as OnSuccessContext,
))
await options.onSuccess?.(
newData,
vars,
// NOTE: cast is safe because of the satisfies above
// using a spread also works
context as OnSuccessContext,
)
if (currentEntry.pending === currentCall) {
currentEntry.state.value = {
status: 'success',
data: newData,
error: null,
}
}
} catch (newError: any) {
currentError = newError
await options.onError?.(newError, vars, context)
if (currentEntry.pending === currentCall) {
currentEntry.state.value = {
status: 'error',
data: currentEntry.state.value.data,
error: newError,
}
}
throw newError
} finally {
await options.onSettled?.(currentData, currentError, vars, context)
currentEntry.asyncStatus.value = 'idle'
}
return currentData
}
return { ensure, ensureDefinedMutation, caches, mutate }
},
)