Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

createMutationController.ts

363 lines9.1 KB

1import {
2 MutationObserver,
3 type DefaultError,
4 type MutateFunction,
5 type MutationObserverOptions,
6 type MutationObserverResult,
7} from '@tanstack/query-core'
8import type { QueryClient } from '@tanstack/query-core'
9import type { ReactiveControllerHost } from 'lit'
10import {
11 createValueAccessor,
12 readAccessor,
13 type Accessor,
14 type ValueAccessor,
15} from './accessor.js'
16import { createMissingQueryClientError } from './context.js'
17import { BaseController } from './controllers/BaseController.js'
18​
19/**
20 * Options accepted by `createMutationController`.
21 *
22 * This is the Lit adapter shape for `MutationObserverOptions`. Pass it directly
23 * or through an `Accessor` when the options depend on Lit host state.
24 */
25export type CreateMutationOptions<
26 TData = unknown,
27 TError = DefaultError,
28 TVariables = void,
29 TOnMutateResult = unknown,
30> = MutationObserverOptions<TData, TError, TVariables, TOnMutateResult>
31​
32/**
33 * Accessor returned by `createMutationController`.
34 *
35 * Call the accessor or read its `current` property to get the latest mutation
36 * result. The attached methods delegate to the active mutation observer.
37 */
38export type MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> =
39 ValueAccessor<
40 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
41 > & {
42 /**
43 * Starts the mutation and swallows the returned promise.
44 *
45 * Throws synchronously if no `QueryClient` can be resolved.
46 */
47 mutate: (
48 ...args: Parameters<
49 MutateFunction<TData, TError, TVariables, TOnMutateResult>
50 >
51 ) => void
52 /**
53 * Starts the mutation and returns the observer promise.
54 *
55 * Rejects if no `QueryClient` can be resolved.
56 */
57 mutateAsync: MutationObserverResult<
58 TData,
59 TError,
60 TVariables,
61 TOnMutateResult
62 >['mutate']
63 /** Resets the mutation observer to its idle state. */
64 reset: MutationObserverResult<
65 TData,
66 TError,
67 TVariables,
68 TOnMutateResult
69 >['reset']
70 /** Removes the controller from its Lit host and unsubscribes observers. */
71 destroy: () => void
72 }
73​
74function createIdleMutationResult<
75 TData,
76 TError,
77 TVariables,
78 TOnMutateResult,
79>(): MutationObserverResult<TData, TError, TVariables, TOnMutateResult> {
80 return {
81 context: undefined,
82 data: undefined,
83 error: null,
84 failureCount: 0,
85 failureReason: null,
86 isError: false,
87 isIdle: true,
88 isPending: false,
89 isPaused: false,
90 isSuccess: false,
91 status: 'idle',
92 submittedAt: 0,
93 variables: undefined,
94 mutate: (() =>
95 Promise.reject(
96 createMissingQueryClientError(),
97 )) as MutationObserverResult<
98 TData,
99 TError,
100 TVariables,
101 TOnMutateResult
102 >['mutate'],
103 reset: (() => undefined) as MutationObserverResult<
104 TData,
105 TError,
106 TVariables,
107 TOnMutateResult
108 >['reset'],
109 } as MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
111​
112class MutationController<
113 TData,
114 TError,
115 TVariables,
116 TOnMutateResult,
117> extends BaseController<
118 MutationObserverResult<TData, TError, TVariables, TOnMutateResult>
119> {
120 private readonly options: Accessor<
121 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
122 >
123 private observer:
124 | MutationObserver<TData, TError, TVariables, TOnMutateResult>
125 | undefined
126 private unsubscribe: (() => void) | undefined
127 private queryClient: QueryClient | undefined
128​
129 constructor(
130 host: ReactiveControllerHost,
131 options: Accessor<
132 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
133 >,
134 queryClient?: QueryClient,
135 ) {
136 super(host, createIdleMutationResult(), queryClient)
137 this.options = options
138​
139 if (!queryClient) {
140 return
141 }
142​
143 if (typeof options === 'function') {
144 return
145 }
146​
147 const observer = new MutationObserver(
148 queryClient,
149 this.defaultOptions(queryClient),
150 )
151 this.queryClient = queryClient
152 this.observer = observer
153 this.result = observer.getCurrentResult()
154 }
155​
156 protected onConnected(): void {
157 if (!this.syncClient()) {
158 return
159 }
160​
161 this.refreshOptions()
162 this.subscribe()
163 if (this.observer) {
164 this.setResult(this.observer.getCurrentResult())
165 }
166 }
167​
168 protected onDisconnected(): void {
169 this.unsubscribeObserver()
170 this.syncClient()
171 }
172​
173 protected onHostUpdate(): void {
174 if (typeof this.options !== 'function') {
175 return
176 }
177​
178 this.refreshOptions()
179 }
180​
181 protected onQueryClientChanged(): void {
182 if (!this.syncClient() || !this.connectedState) {
183 return
184 }
185​
186 this.refreshOptions()
187 this.subscribe()
188 if (this.observer) {
189 this.setResult(this.observer.getCurrentResult())
190 }
191 }
192​
193 mutate = (
194 ...args: Parameters<
195 MutateFunction<TData, TError, TVariables, TOnMutateResult>
196 >
197 ): void => {
198 if (!this.syncClient() || !this.observer) {
199 throw createMissingQueryClientError()
200 }
201​
202 void this.observer.mutate(args[0] as TVariables, args[1]).catch(() => {
203 // Intentionally swallow in sync mutate path.
204 })
205 }
206​
207 mutateAsync: MutationObserverResult<
208 TData,
209 TError,
210 TVariables,
211 TOnMutateResult
212 >['mutate'] = (...args) => {
213 if (!this.syncClient() || !this.observer) {
214 return Promise.reject(createMissingQueryClientError())
215 }
216​
217 return this.observer.mutate(args[0] as TVariables, args[1])
218 }
219​
220 reset: MutationObserverResult<
221 TData,
222 TError,
223 TVariables,
224 TOnMutateResult
225 >['reset'] = () => {
226 if (!this.syncClient() || !this.observer) {
227 return
228 }
229​
230 this.observer.reset()
231 this.setResult(this.observer.getCurrentResult())
232 }
233​
234 private subscribe(): void {
235 if (!this.observer) {
236 return
237 }
238​
239 if (this.unsubscribe) {
240 return
241 }
242​
243 this.unsubscribe = this.observer.subscribe((next) => {
244 this.setResult(next)
245 })
246 }
247​
248 private unsubscribeObserver(): void {
249 this.unsubscribe?.()
250 this.unsubscribe = undefined
251 }
252​
253 private syncClient(): boolean {
254 const nextClient = this.tryGetQueryClient()
255 if (!nextClient) {
256 this.unsubscribeObserver()
257 this.queryClient = undefined
258 this.observer = undefined
259 this.setResult(createIdleMutationResult())
260 return false
261 }
262​
263 if (nextClient === this.queryClient) {
264 return true
265 }
266​
267 this.unsubscribeObserver()
268 this.queryClient = nextClient
269 this.observer = new MutationObserver(
270 this.queryClient,
271 this.defaultOptions(this.queryClient),
272 )
273 this.setResult(this.observer.getCurrentResult())
274 return true
275 }
276​
277 private refreshOptions(): boolean {
278 if (!this.syncClient() || !this.observer || !this.queryClient) {
279 return false
280 }
281​
282 this.observer.setOptions(this.defaultOptions())
283 this.setResult(this.observer.getCurrentResult())
284 return true
285 }
286​
287 private defaultOptions(
288 client = this.queryClient,
289 ): MutationObserverOptions<TData, TError, TVariables, TOnMutateResult> {
290 if (!client) {
291 throw createMissingQueryClientError()
292 }
293​
294 return client.defaultMutationOptions(readAccessor(this.options))
295 }
297​
298/**
299 * Creates a Lit reactive controller that subscribes the host to a mutation.
300 *
301 * The returned accessor is callable and also exposes `current`, `mutate`,
302 * `mutateAsync`, `reset`, and `destroy`. When `options` is a function, it is
303 * re-read during host updates so mutation options can follow reactive host
304 * state.
305 *
306 * If `queryClient` is omitted, the controller resolves the client from the
307 * nearest connected `QueryClientProvider`.
308 *
309 * @param host - The Lit reactive controller host that owns the mutation
310 * subscription.
311 * @param options - Mutation observer options, or a getter that returns options.
312 * @param queryClient - Optional explicit query client. Provide this for
313 * controllers that should not resolve a client from Lit context.
314 * @returns An accessor for the latest mutation result with mutation helper
315 * methods.
316 *
317 * @example
318 * ```ts
319 * import { LitElement, html } from 'lit'
320 * import { createMutationController } from '@tanstack/lit-query'
321 *
322 * class AddTodoForm extends LitElement {
323 * private readonly addTodo = createMutationController(this, {
324 * mutationFn: (title: string) =>
325 * fetch('/api/todos', { method: 'POST', body: JSON.stringify({ title }) }),
326 * })
327 *
328 * render() {
329 * const mutation = this.addTodo()
330 *
331 * return html`
332 * <button ?disabled=${mutation.isPending} @click=${() => this.addTodo.mutate('Ship docs')}>
333 * Add todo
334 * </button>
335 * `
336 * }
337 * }
338 * ```
339 */
340export function createMutationController<
341 TData = unknown,
342 TError = DefaultError,
343 TVariables = void,
344 TOnMutateResult = unknown,
345>(
346 host: ReactiveControllerHost,
347 options: Accessor<
348 CreateMutationOptions<TData, TError, TVariables, TOnMutateResult>
349 >,
350 queryClient?: QueryClient,
351): MutationResultAccessor<TData, TError, TVariables, TOnMutateResult> {
352 const controller = new MutationController(host, options, queryClient)
353​
354 return Object.assign(
355 createValueAccessor(() => controller.current),
356 {
357 mutate: controller.mutate,
358 mutateAsync: controller.mutateAsync,
359 reset: controller.reset,
360 destroy: () => controller.destroy(),
361 },
362 )