Repository navigation
Expand file tree
/
Copy pathmutationObserver.ts
More file actions
321 lines (293 loc) · 9.58 KB
/
Copy pathmutationObserver.ts
File metadata and controls
321 lines (293 loc) · 9.58 KB
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
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
import { getDefaultState } from './mutation'
import { notifyManager } from './notifyManager'
import { Subscribable } from './subscribable'
import { hashKey, shallowEqualObjects } from './utils'
import type { QueryClient } from './queryClient'
import type {
DefaultError,
MutateOptions,
MutationFunctionContext,
MutationObserverOptions,
MutationObserverResult,
} from './types'
import type { Action, Mutation } from './mutation'
// TYPES
type MutationObserverListener<TData, TError, TVariables, TOnMutateResult> = (
result: MutationObserverResult<TData, TError, TVariables, TOnMutateResult>,
) => void
// CLASS
/**
* Observes a single mutation and derives a `MutationObserverResult` from it.
* A framework hook like `useMutation` creates one `MutationObserver` per hook
* call, keeps it stable across re-renders, calls `setOptions` when the options
* passed to the hook change, subscribes to it to re-render on updates, and
* reads `getCurrentResult()` for the value to return. Calling `mutate()`
* builds a new underlying `Mutation` in the `MutationCache` and executes it.
* @example
* ```ts
* const observer = new MutationObserver(queryClient, {
* mutationFn: (variables: { title: string }) => addPost(variables),
* })
* ```
*/
export class MutationObserver<
TData = unknown,
TError = DefaultError,
TVariables = void,
TOnMutateResult = unknown,
> extends Subscribable<
MutationObserverListener<TData, TError, TVariables, TOnMutateResult>
> {
options!: MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
#client: QueryClient
#currentResult: MutationObserverResult<
TData,
TError,
TVariables,
TOnMutateResult
> = undefined!
#currentMutation?: Mutation<TData, TError, TVariables, TOnMutateResult>
#mutateOptions?: MutateOptions<TData, TError, TVariables, TOnMutateResult>
constructor(
client: QueryClient,
options: MutationObserverOptions<
TData,
TError,
TVariables,
TOnMutateResult
>,
) {
super()
this.#client = client
this.setOptions(options)
this.bindMethods()
this.#updateResult()
}
/**
* Binds the methods of the result (`mutate` and `reset`) to the observer, so they keep working when
* destructured from it.
*/
protected bindMethods(): void {
this.mutate = this.mutate.bind(this)
this.reset = this.reset.bind(this)
}
/**
* Updates the observer's options.
*
* If the new `mutationKey` differs from the previous one (and both were
* defined), the observer is reset, detaching it from the mutation it was
* observing. Otherwise, if the currently observed mutation is still
* `pending`, its options are updated in place as well.
* @param options - The new mutation observer options. They are defaulted with {@link
* QueryClient#defaultMutationOptions} before being applied.
* @example
* ```ts
* observer.setOptions({
* mutationFn: (variables: { title: string }) => addPost(variables),
* onSuccess: (data) => console.log(data),
* })
* ```
*/
setOptions(
options: MutationObserverOptions<
TData,
TError,
TVariables,
TOnMutateResult
>,
) {
const prevOptions = this.options as
| MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
| undefined
this.options = this.#client.defaultMutationOptions(options)
if (!shallowEqualObjects(this.options, prevOptions)) {
this.#client.getMutationCache().notify({
type: 'observerOptionsUpdated',
mutation: this.#currentMutation,
observer: this,
})
}
if (
prevOptions?.mutationKey &&
this.options.mutationKey &&
hashKey(prevOptions.mutationKey) !== hashKey(this.options.mutationKey)
) {
this.reset()
} else if (this.#currentMutation?.state.status === 'pending') {
this.#currentMutation.setOptions(this.options)
}
}
protected override onSubscribe(): void {
if (this.listeners.size === 1 && this.#currentMutation) {
this.#currentMutation.addObserver(this)
this.#updateResult()
}
}
protected override onUnsubscribe(): void {
if (!this.hasListeners()) {
this.#currentMutation?.removeObserver(this)
}
}
/**
* Updates the observer's result when the observed mutation changes, and notifies its listeners.
* @internal
* @param action - The action that updated the observed mutation, passed on to the observer's
* callbacks.
*/
onMutationUpdate(
action: Action<TData, TError, TVariables, TOnMutateResult>,
): void {
this.#updateResult()
this.#notify(action)
}
/**
* Returns the observer's current result, derived from the observed
* mutation's state (or the default, `idle` state if no mutation has been
* built yet, e.g. before the first `mutate()` call or after `reset()`).
* @returns The observer's latest result.
*/
getCurrentResult(): MutationObserverResult<
TData,
TError,
TVariables,
TOnMutateResult
> {
return this.#currentResult
}
/**
* Detaches the observer from the mutation it is currently observing (if
* any) and resets the observed result back to its default, `idle` state.
*
* This does not cancel an in-flight mutation; the mutation itself keeps
* running to completion and its own callbacks still fire, but this
* observer stops reflecting its state and a subsequent `mutate()` call
* will build a brand new mutation.
* @see {@link MutationObserver#mutate}
* @example
* ```ts
* observer.reset()
* ```
*/
reset(): void {
// reset needs to remove the observer from the mutation because there is no way to "get it back"
// another mutate call will yield a new mutation!
this.#currentMutation?.removeObserver(this)
this.#currentMutation = undefined
this.#updateResult()
this.#notify()
}
/**
* Builds a new `Mutation` in the `MutationCache` using the observer's
* current options, detaches this observer from any previously observed
* mutation, attaches it to the new one, and executes it with the given
* variables.
*
* The optional per-call `options` (`onSuccess`/`onError`/`onSettled`) are
* invoked once the mutation settles, in addition to any callbacks defined
* on the observer's own options.
* @param variables - The variables passed to the `mutationFn`.
* @param options - Per-call `onSuccess`, `onError`, and `onSettled` callbacks.
* @returns A promise that resolves with the mutation's data, or rejects with its error.
* @example
* ```ts
* await observer.mutate(
* { title: 'New post' },
* { onSuccess: (data) => console.log(data) },
* )
* ```
*/
mutate(
variables: TVariables,
options?: MutateOptions<TData, TError, TVariables, TOnMutateResult>,
): Promise<TData> {
this.#mutateOptions = options
this.#currentMutation?.removeObserver(this)
this.#currentMutation = this.#client
.getMutationCache()
.build(this.#client, this.options)
this.#currentMutation.addObserver(this)
return this.#currentMutation.execute(variables)
}
#updateResult(): void {
const state =
this.#currentMutation?.state ??
getDefaultState<TData, TError, TVariables, TOnMutateResult>()
this.#currentResult = {
...state,
isPending: state.status === 'pending',
isSuccess: state.status === 'success',
isError: state.status === 'error',
isIdle: state.status === 'idle',
mutate: this.mutate,
reset: this.reset,
} as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
}
#notify(action?: Action<TData, TError, TVariables, TOnMutateResult>): void {
notifyManager.batch(() => {
// First trigger the mutate callbacks
// Snapshot mutateOptions before dispatching — a callback (e.g. onSuccess)
// may call mutate() again, which overwrites this.#mutateOptions in place.
// Without the snapshot, onSettled would fire with the *next* mutation's
// options but the *current* mutation's data/variables.
const mutateOptions = this.#mutateOptions
if (mutateOptions && this.hasListeners()) {
const variables = this.#currentResult.variables!
const onMutateResult = this.#currentResult.context
const context = {
client: this.#client,
meta: this.options.meta,
mutationKey: this.options.mutationKey,
} satisfies MutationFunctionContext
if (action?.type === 'success') {
try {
mutateOptions.onSuccess?.(
action.data,
variables,
onMutateResult,
context,
)
} catch (e) {
void Promise.reject(e)
}
try {
mutateOptions.onSettled?.(
action.data,
null,
variables,
onMutateResult,
context,
)
} catch (e) {
void Promise.reject(e)
}
} else if (action?.type === 'error') {
try {
mutateOptions.onError?.(
action.error,
variables,
onMutateResult,
context,
)
} catch (e) {
void Promise.reject(e)
}
try {
mutateOptions.onSettled?.(
undefined,
action.error,
variables,
onMutateResult,
context,
)
} catch (e) {
void Promise.reject(e)
}
}
}
// Then trigger the listeners
this.listeners.forEach((listener) => {
listener(this.#currentResult)
})
})
}
}