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

createQueryController.ts

379 lines10.1 KB

1import {
2 QueryObserver,
3 type DefaultError,
4 type DefaultedQueryObserverOptions,
5 type QueryKey,
6 type QueryObserverOptions,
7 type QueryObserverResult,
8} from '@tanstack/query-core'
9import type { QueryClient } from '@tanstack/query-core'
10import type { ReactiveControllerHost } from 'lit'
11import {
12 createValueAccessor,
13 readAccessor,
14 type Accessor,
15 type ValueAccessor,
16} from './accessor.js'
17import { createMissingQueryClientError } from './context.js'
18import { BaseController } from './controllers/BaseController.js'
19import { QueryObserverResultTracker } from './queryObserverResultTracker.js'
20​
21/**
22 * Options accepted by `createQueryController`.
23 *
24 * This is the Lit adapter shape for `QueryObserverOptions`. It can be passed
25 * directly to `createQueryController`, or wrapped in an `Accessor` when the
26 * options depend on Lit host state.
27 */
28export type CreateQueryOptions<
29 TQueryFnData = unknown,
30 TError = DefaultError,
31 TData = TQueryFnData,
32 TQueryData = TQueryFnData,
33 TQueryKey extends QueryKey = QueryKey,
34> = QueryObserverOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
35​
36/**
37 * Accessor returned by `createQueryController`.
38 *
39 * Call the accessor or read its `current` property to get the latest query
40 * result. The attached methods delegate to the active query observer.
41 */
42export type QueryResultAccessor<TData, TError> = ValueAccessor<
43 QueryObserverResult<TData, TError>
44> & {
45 /** Refetches the current query. */
46 refetch: QueryObserverResult<TData, TError>['refetch']
47 /** Resolves with an optimistic query result, fetching first when needed. */
48 suspense: () => Promise<QueryObserverResult<TData, TError>>
49 /** Removes the controller from its Lit host and unsubscribes observers. */
50 destroy: () => void
52​
53function createPendingQueryResult<TData, TError>(): QueryObserverResult<
54 TData,
55 TError
56> {
57 return {
58 data: undefined,
59 dataUpdatedAt: 0,
60 error: null,
61 errorUpdatedAt: 0,
62 failureCount: 0,
63 failureReason: null,
64 errorUpdateCount: 0,
65 isError: false,
66 isFetched: false,
67 isFetchedAfterMount: false,
68 isFetching: false,
69 isInitialLoading: false,
70 isLoading: false,
71 isLoadingError: false,
72 isPaused: false,
73 isPending: true,
74 isPlaceholderData: false,
75 isRefetchError: false,
76 isRefetching: false,
77 isStale: true,
78 isEnabled: true,
79 isSuccess: false,
80 fetchStatus: 'idle',
81 status: 'pending',
82 refetch: (() =>
83 Promise.reject(createMissingQueryClientError())) as QueryObserverResult<
84 TData,
85 TError
86 >['refetch'],
87 promise: Promise.resolve(undefined as never),
88 } as unknown as QueryObserverResult<TData, TError>
90​
91class QueryController<
92 TQueryFnData,
93 TError,
94 TData,
95 TQueryData,
96 TQueryKey extends QueryKey,
97> extends BaseController<QueryObserverResult<TData, TError>> {
98 private readonly options: Accessor<
99 CreateQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
100 >
101 private observer:
102 | QueryObserver<TQueryFnData, TError, TData, TQueryData, TQueryKey>
103 | undefined
104 private readonly resultTracker = new QueryObserverResultTracker<
105 QueryObserverResult<TData, TError>
106 >()
107 private unsubscribe: (() => void) | undefined
108 private queryClient: QueryClient | undefined
109​
110 constructor(
111 host: ReactiveControllerHost,
112 options: Accessor<
113 CreateQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
114 >,
115 queryClient?: QueryClient,
116 ) {
117 const initialClient = queryClient
118 super(host, createPendingQueryResult(), queryClient)
119 this.options = options
120​
121 if (!initialClient) {
122 return
123 }
124​
125 if (typeof options === 'function') {
126 return
127 }
128​
129 const defaulted = this.defaultOptions(initialClient)
130 const observer = new QueryObserver(initialClient, defaulted)
131 this.queryClient = initialClient
132 this.observer = observer
133 this.assignObserverResult(observer.getOptimisticResult(defaulted))
134 }
135​
136 protected onConnected(): void {
137 if (!this.syncClient()) {
138 return
139 }
140​
141 this.refreshOptions()
142 this.subscribe()
143 this.observer?.updateResult()
144 if (this.observer) {
145 this.setObserverResult(this.observer.getCurrentResult())
146 }
147 }
148​
149 protected onDisconnected(): void {
150 this.unsubscribeObserver()
151 this.syncClient()
152 }
153​
154 protected onHostUpdate(): void {
155 if (typeof this.options !== 'function') {
156 return
157 }
158​
159 this.refreshOptions()
160 }
161​
162 protected onQueryClientChanged(): void {
163 if (!this.syncClient()) {
164 return
165 }
166​
167 if (!this.connectedState) {
168 return
169 }
170​
171 this.refreshOptions()
172 this.subscribe()
173 this.observer?.updateResult()
174 if (this.observer) {
175 this.setObserverResult(this.observer.getCurrentResult())
176 }
177 }
178​
179 refetch: QueryObserverResult<TData, TError>['refetch'] = (...args) => {
180 if (!this.applyOptions() || !this.observer) {
181 return Promise.reject(createMissingQueryClientError())
182 }
183​
184 return this.observer.refetch(...args)
185 }
186​
187 suspense = async (): Promise<QueryObserverResult<TData, TError>> => {
188 if (!this.syncClient() || !this.observer || !this.queryClient) {
189 throw createMissingQueryClientError()
190 }
191​
192 const options = this.defaultOptions(this.queryClient)
193 this.observer.setOptions(options)
194 const optimistic = this.observer.getOptimisticResult(options)
195 if (options.enabled !== false && optimistic.isStale) {
196 return this.observer.fetchOptimistic(options)
197 }
198​
199 return optimistic
200 }
201​
202 readCurrent(): QueryObserverResult<TData, TError> {
203 if (this.observer) {
204 this.assignObserverResult(this.observer.getCurrentResult())
205 }
206​
207 return this.current
208 }
209​
210 private subscribe(): void {
211 if (!this.observer) {
212 return
213 }
214​
215 if (this.unsubscribe) {
216 return
217 }
218​
219 this.unsubscribe = this.observer.subscribe((next) => {
220 this.setObserverResult(next)
221 })
222 }
223​
224 private unsubscribeObserver(): void {
225 this.unsubscribe?.()
226 this.unsubscribe = undefined
227 }
228​
229 private syncClient(): boolean {
230 const nextClient = this.tryGetQueryClient()
231 if (!nextClient) {
232 this.unsubscribeObserver()
233 this.queryClient = undefined
234 this.observer = undefined
235 this.resultTracker.reset()
236 this.setResult(createPendingQueryResult())
237 return false
238 }
239​
240 if (nextClient === this.queryClient && this.observer) {
241 return true
242 }
243​
244 this.unsubscribeObserver()
245 this.queryClient = nextClient
246 const options = this.defaultOptions()
247 this.observer = new QueryObserver(this.queryClient, options)
248 this.setObserverResult(this.observer.getOptimisticResult(options))
249 return true
250 }
251​
252 private applyOptions(): boolean {
253 if (!this.syncClient() || !this.observer) {
254 return false
255 }
256​
257 const options = this.defaultOptions(this.queryClient)
258 this.observer.setOptions(options)
259 return true
260 }
261​
262 private refreshOptions(): boolean {
263 if (!this.applyOptions() || !this.observer) {
264 return false
265 }
266​
267 this.setObserverResult(this.observer.getCurrentResult())
268 return true
269 }
270​
271 private assignObserverResult(
272 result: QueryObserverResult<TData, TError>,
273 ): void {
274 const trackedResult = this.resultTracker.update(this.observer, result)
275 if (trackedResult) {
276 this.result = trackedResult
277 }
278 }
279​
280 private setObserverResult(result: QueryObserverResult<TData, TError>): void {
281 const trackedResult = this.resultTracker.update(this.observer, result)
282 if (trackedResult) {
283 this.setResult(trackedResult)
284 }
285 }
286​
287 private defaultOptions(
288 client = this.queryClient,
289 ): DefaultedQueryObserverOptions<
290 TQueryFnData,
291 TError,
292 TData,
293 TQueryData,
294 TQueryKey
295 > {
296 const resolvedClient = client ?? this.tryGetQueryClient()
297 if (!resolvedClient) {
298 throw createMissingQueryClientError()
299 }
300​
301 this.queryClient = resolvedClient
302 const defaulted = resolvedClient.defaultQueryOptions(
303 readAccessor(this.options),
304 ) as DefaultedQueryObserverOptions<
305 TQueryFnData,
306 TError,
307 TData,
308 TQueryData,
309 TQueryKey
310 >
311 ;(defaulted as { _optimisticResults?: 'optimistic' })._optimisticResults =
312 'optimistic'
313 return defaulted
314 }
316​
317/**
318 * Creates a Lit reactive controller that subscribes the host to a single query.
319 *
320 * The returned accessor is callable and also exposes `current`, `refetch`,
321 * `suspense`, and `destroy`. When `options` is a function, it is re-read during
322 * host updates so query keys and options can follow reactive host state.
323 *
324 * If `queryClient` is omitted, the controller resolves the client from the
325 * nearest connected `QueryClientProvider`.
326 *
327 * @param host - The Lit reactive controller host that owns the query
328 * subscription.
329 * @param options - Query observer options, or a getter that returns options.
330 * @param queryClient - Optional explicit query client. Provide this for
331 * controllers that should not resolve a client from Lit context.
332 * @returns An accessor for the latest query result with query helper methods.
333 *
334 * @example
335 * ```ts
336 * import { LitElement, html } from 'lit'
337 * import { createQueryController } from '@tanstack/lit-query'
338 *
339 * class TodosView extends LitElement {
340 * private readonly todos = createQueryController(this, {
341 * queryKey: ['todos'],
342 * queryFn: async () => fetch('/api/todos').then((r) => r.json()),
343 * })
344 *
345 * render() {
346 * const query = this.todos()
347 *
348 * if (query.isPending) return html`Loading...`
349 * if (query.isError) return html`Error`
350 *
351 * return html`<ul>${query.data.map((todo) => html`<li>${todo.title}</li>`)}</ul>`
352 * }
353 * }
354 * ```
355 */
356export function createQueryController<
357 TQueryFnData = unknown,
358 TError = DefaultError,
359 TData = TQueryFnData,
360 TQueryData = TQueryFnData,
361 TQueryKey extends QueryKey = QueryKey,
362>(
363 host: ReactiveControllerHost,
364 options: Accessor<
365 CreateQueryOptions<TQueryFnData, TError, TData, TQueryData, TQueryKey>
366 >,
367 queryClient?: QueryClient,
368): QueryResultAccessor<TData, TError> {
369 const controller = new QueryController(host, options, queryClient)
370​
371 return Object.assign(
372 createValueAccessor(() => controller.readCurrent()),
373 {
374 refetch: controller.refetch,
375 suspense: controller.suspense,
376 destroy: () => controller.destroy(),
377 },
378 )