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

query.ts

694 lines22.2 KB

1import { QueryObserver } from "@tanstack/query-core"
2import {
3 GetKeyRequiredError,
4 QueryClientRequiredError,
5 QueryFnRequiredError,
6 QueryKeyRequiredError,
7} from "./errors"
8import { createWriteUtils } from "./manual-sync"
9import type {
10 QueryClient,
11 QueryFunctionContext,
12 QueryKey,
13 QueryObserverOptions,
14} from "@tanstack/query-core"
15import type {
16 ChangeMessage,
17 CollectionConfig,
18 DeleteMutationFn,
19 DeleteMutationFnParams,
20 InsertMutationFn,
21 InsertMutationFnParams,
22 SyncConfig,
23 UpdateMutationFn,
24 UpdateMutationFnParams,
25 UtilsRecord,
26} from "@tanstack/db"
27import type { StandardSchemaV1 } from "@standard-schema/spec"
28​
29// Re-export for external use
30export type { SyncOperation } from "./manual-sync"
31​
32// Schema output type inference helper (matches electric.ts pattern)
33type InferSchemaOutput<T> = T extends StandardSchemaV1
34 ? StandardSchemaV1.InferOutput<T> extends object
35 ? StandardSchemaV1.InferOutput<T>
36 : Record<string, unknown>
37 : Record<string, unknown>
38​
39// QueryFn return type inference helper
40type InferQueryFnOutput<TQueryFn> = TQueryFn extends (
41 context: QueryFunctionContext<any>
42) => Promise<Array<infer TItem>>
43 ? TItem extends object
44 ? TItem
45 : Record<string, unknown>
46 : Record<string, unknown>
47​
48// Type resolution system with priority order (matches electric.ts pattern)
49type ResolveType<
50 TExplicit extends object | unknown = unknown,
51 TSchema extends StandardSchemaV1 = never,
52 TQueryFn = unknown,
53> = unknown extends TExplicit
54 ? [TSchema] extends [never]
55 ? InferQueryFnOutput<TQueryFn>
56 : InferSchemaOutput<TSchema>
57 : TExplicit
58​
59/**
60 * Configuration options for creating a Query Collection
61 * @template TExplicit - The explicit type of items stored in the collection (highest priority)
62 * @template TSchema - The schema type for validation and type inference (second priority)
63 * @template TQueryFn - The queryFn type for inferring return type (third priority)
64 * @template TError - The type of errors that can occur during queries
65 * @template TQueryKey - The type of the query key
66 */
67export interface QueryCollectionConfig<
68 TExplicit extends object = object,
69 TSchema extends StandardSchemaV1 = never,
70 TQueryFn extends (
71 context: QueryFunctionContext<any>
72 ) => Promise<Array<any>> = (
73 context: QueryFunctionContext<any>
74 ) => Promise<Array<any>>,
75 TError = unknown,
76 TQueryKey extends QueryKey = QueryKey,
77> {
78 /** The query key used by TanStack Query to identify this query */
79 queryKey: TQueryKey
80 /** Function that fetches data from the server. Must return the complete collection state */
81 queryFn: TQueryFn extends (
82 context: QueryFunctionContext<TQueryKey>
83 ) => Promise<Array<any>>
84 ? TQueryFn
85 : (
86 context: QueryFunctionContext<TQueryKey>
87 ) => Promise<Array<ResolveType<TExplicit, TSchema, TQueryFn>>>
88​
89 /** The TanStack Query client instance */
90 queryClient: QueryClient
91​
92 // Query-specific options
93 /** Whether the query should automatically run (default: true) */
94 enabled?: boolean
95 refetchInterval?: QueryObserverOptions<
96 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
97 TError,
98 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
99 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
100 TQueryKey
101 >[`refetchInterval`]
102 retry?: QueryObserverOptions<
103 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
104 TError,
105 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
106 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
107 TQueryKey
108 >[`retry`]
109 retryDelay?: QueryObserverOptions<
110 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
111 TError,
112 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
113 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
114 TQueryKey
115 >[`retryDelay`]
116 staleTime?: QueryObserverOptions<
117 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
118 TError,
119 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
120 Array<ResolveType<TExplicit, TSchema, TQueryFn>>,
121 TQueryKey
122 >[`staleTime`]
123​
124 // Standard Collection configuration properties
125 /** Unique identifier for the collection */
126 id?: string
127 /** Function to extract the unique key from an item */
128 getKey: CollectionConfig<ResolveType<TExplicit, TSchema, TQueryFn>>[`getKey`]
129 /** Schema for validating items */
130 schema?: TSchema
131 sync?: CollectionConfig<ResolveType<TExplicit, TSchema, TQueryFn>>[`sync`]
132 startSync?: CollectionConfig<
133 ResolveType<TExplicit, TSchema, TQueryFn>
134 >[`startSync`]
135​
136 // Direct persistence handlers
137 /**
138 * Optional asynchronous handler function called before an insert operation
139 * @param params Object containing transaction and collection information
140 * @returns Promise resolving to void or { refetch?: boolean } to control refetching
141 * @example
142 * // Basic query collection insert handler
143 * onInsert: async ({ transaction }) => {
144 * const newItem = transaction.mutations[0].modified
145 * await api.createTodo(newItem)
146 * // Automatically refetches query after insert
147 * }
148 *
149 * @example
150 * // Insert handler with refetch control
151 * onInsert: async ({ transaction }) => {
152 * const newItem = transaction.mutations[0].modified
153 * await api.createTodo(newItem)
154 * return { refetch: false } // Skip automatic refetch
155 * }
156 *
157 * @example
158 * // Insert handler with multiple items
159 * onInsert: async ({ transaction }) => {
160 * const items = transaction.mutations.map(m => m.modified)
161 * await api.createTodos(items)
162 * // Will refetch query to get updated data
163 * }
164 *
165 * @example
166 * // Insert handler with error handling
167 * onInsert: async ({ transaction }) => {
168 * try {
169 * const newItem = transaction.mutations[0].modified
170 * await api.createTodo(newItem)
171 * } catch (error) {
172 * console.error('Insert failed:', error)
173 * throw error // Transaction will rollback optimistic changes
174 * }
175 * }
176 */
177 onInsert?: InsertMutationFn<ResolveType<TExplicit, TSchema, TQueryFn>>
178​
179 /**
180 * Optional asynchronous handler function called before an update operation
181 * @param params Object containing transaction and collection information
182 * @returns Promise resolving to void or { refetch?: boolean } to control refetching
183 * @example
184 * // Basic query collection update handler
185 * onUpdate: async ({ transaction }) => {
186 * const mutation = transaction.mutations[0]
187 * await api.updateTodo(mutation.original.id, mutation.changes)
188 * // Automatically refetches query after update
189 * }
190 *
191 * @example
192 * // Update handler with multiple items
193 * onUpdate: async ({ transaction }) => {
194 * const updates = transaction.mutations.map(m => ({
195 * id: m.key,
196 * changes: m.changes
197 * }))
198 * await api.updateTodos(updates)
199 * // Will refetch query to get updated data
200 * }
201 *
202 * @example
203 * // Update handler with manual refetch
204 * onUpdate: async ({ transaction, collection }) => {
205 * const mutation = transaction.mutations[0]
206 * await api.updateTodo(mutation.original.id, mutation.changes)
207 *
208 * // Manually trigger refetch
209 * await collection.utils.refetch()
210 *
211 * return { refetch: false } // Skip automatic refetch
212 * }
213 *
214 * @example
215 * // Update handler with related collection refetch
216 * onUpdate: async ({ transaction, collection }) => {
217 * const mutation = transaction.mutations[0]
218 * await api.updateTodo(mutation.original.id, mutation.changes)
219 *
220 * // Refetch related collections when this item changes
221 * await Promise.all([
222 * collection.utils.refetch(), // Refetch this collection
223 * usersCollection.utils.refetch(), // Refetch users
224 * tagsCollection.utils.refetch() // Refetch tags
225 * ])
226 *
227 * return { refetch: false } // Skip automatic refetch since we handled it manually
228 * }
229 */
230 onUpdate?: UpdateMutationFn<ResolveType<TExplicit, TSchema, TQueryFn>>
231​
232 /**
233 * Optional asynchronous handler function called before a delete operation
234 * @param params Object containing transaction and collection information
235 * @returns Promise resolving to void or { refetch?: boolean } to control refetching
236 * @example
237 * // Basic query collection delete handler
238 * onDelete: async ({ transaction }) => {
239 * const mutation = transaction.mutations[0]
240 * await api.deleteTodo(mutation.original.id)
241 * // Automatically refetches query after delete
242 * }
243 *
244 * @example
245 * // Delete handler with refetch control
246 * onDelete: async ({ transaction }) => {
247 * const mutation = transaction.mutations[0]
248 * await api.deleteTodo(mutation.original.id)
249 * return { refetch: false } // Skip automatic refetch
250 * }
251 *
252 * @example
253 * // Delete handler with multiple items
254 * onDelete: async ({ transaction }) => {
255 * const keysToDelete = transaction.mutations.map(m => m.key)
256 * await api.deleteTodos(keysToDelete)
257 * // Will refetch query to get updated data
258 * }
259 *
260 * @example
261 * // Delete handler with related collection refetch
262 * onDelete: async ({ transaction, collection }) => {
263 * const mutation = transaction.mutations[0]
264 * await api.deleteTodo(mutation.original.id)
265 *
266 * // Refetch related collections when this item is deleted
267 * await Promise.all([
268 * collection.utils.refetch(), // Refetch this collection
269 * usersCollection.utils.refetch(), // Refetch users
270 * projectsCollection.utils.refetch() // Refetch projects
271 * ])
272 *
273 * return { refetch: false } // Skip automatic refetch since we handled it manually
274 * }
275 */
276 onDelete?: DeleteMutationFn<ResolveType<TExplicit, TSchema, TQueryFn>>
277​
278 /**
279 * Metadata to pass to the query.
280 * Available in queryFn via context.meta
281 *
282 * @example
283 * // Using meta for error context
284 * queryFn: async (context) => {
285 * try {
286 * return await api.getTodos(userId)
287 * } catch (error) {
288 * // Use meta for better error messages
289 * throw new Error(
290 * context.meta?.errorMessage || 'Failed to load todos'
291 * )
292 * }
293 * },
294 * meta: {
295 * errorMessage: `Failed to load todos for user ${userId}`
296 * }
297 */
298 meta?: Record<string, unknown>
300​
301/**
302 * Type for the refetch utility function
303 */
304export type RefetchFn = () => Promise<void>
305​
306/**
307 * Utility methods available on Query Collections for direct writes and manual operations.
308 * Direct writes bypass the normal query/mutation flow and write directly to the synced data store.
309 * @template TItem - The type of items stored in the collection
310 * @template TKey - The type of the item keys
311 * @template TInsertInput - The type accepted for insert operations
312 */
313export interface QueryCollectionUtils<
314 TItem extends object = Record<string, unknown>,
315 TKey extends string | number = string | number,
316 TInsertInput extends object = TItem,
317> extends UtilsRecord {
318 /** Manually trigger a refetch of the query */
319 refetch: RefetchFn
320 /** Insert one or more items directly into the synced data store without triggering a query refetch or optimistic update */
321 writeInsert: (data: TInsertInput | Array<TInsertInput>) => void
322 /** Update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
323 writeUpdate: (updates: Partial<TItem> | Array<Partial<TItem>>) => void
324 /** Delete one or more items directly from the synced data store without triggering a query refetch or optimistic update */
325 writeDelete: (keys: TKey | Array<TKey>) => void
326 /** Insert or update one or more items directly in the synced data store without triggering a query refetch or optimistic update */
327 writeUpsert: (data: Partial<TItem> | Array<Partial<TItem>>) => void
328 /** Execute multiple write operations as a single atomic batch to the synced data store */
329 writeBatch: (callback: () => void) => void
331​
332/**
333 * Creates query collection options for use with a standard Collection.
334 * This integrates TanStack Query with TanStack DB for automatic synchronization.
335 *
336 * Supports automatic type inference following the priority order:
337 * 1. Explicit type (highest priority)
338 * 2. Schema inference (second priority)
339 * 3. QueryFn return type inference (third priority)
340 * 4. Fallback to Record<string, unknown>
341 *
342 * @template TExplicit - The explicit type of items in the collection (highest priority)
343 * @template TSchema - The schema type for validation and type inference (second priority)
344 * @template TQueryFn - The queryFn type for inferring return type (third priority)
345 * @template TError - The type of errors that can occur during queries
346 * @template TQueryKey - The type of the query key
347 * @template TKey - The type of the item keys
348 * @template TInsertInput - The type accepted for insert operations
349 * @param config - Configuration options for the Query collection
350 * @returns Collection options with utilities for direct writes and manual operations
351 *
352 * @example
353 * // Type inferred from queryFn return type (NEW!)
354 * const todosCollection = createCollection(
355 * queryCollectionOptions({
356 * queryKey: ['todos'],
357 * queryFn: async () => {
358 * const response = await fetch('/api/todos')
359 * return response.json() as Todo[] // Type automatically inferred!
360 * },
361 * queryClient,
362 * getKey: (item) => item.id, // item is typed as Todo
363 * })
364 * )
365 *
366 * @example
367 * // Explicit type (highest priority)
368 * const todosCollection = createCollection<Todo>(
369 * queryCollectionOptions({
370 * queryKey: ['todos'],
371 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
372 * queryClient,
373 * getKey: (item) => item.id,
374 * })
375 * )
376 *
377 * @example
378 * // Schema inference (second priority)
379 * const todosCollection = createCollection(
380 * queryCollectionOptions({
381 * queryKey: ['todos'],
382 * queryFn: async () => fetch('/api/todos').then(r => r.json()),
383 * queryClient,
384 * schema: todoSchema, // Type inferred from schema
385 * getKey: (item) => item.id,
386 * })
387 * )
388 *
389 * @example
390 * // With persistence handlers
391 * const todosCollection = createCollection(
392 * queryCollectionOptions({
393 * queryKey: ['todos'],
394 * queryFn: fetchTodos,
395 * queryClient,
396 * getKey: (item) => item.id,
397 * onInsert: async ({ transaction }) => {
398 * await api.createTodos(transaction.mutations.map(m => m.modified))
399 * },
400 * onUpdate: async ({ transaction }) => {
401 * await api.updateTodos(transaction.mutations)
402 * },
403 * onDelete: async ({ transaction }) => {
404 * await api.deleteTodos(transaction.mutations.map(m => m.key))
405 * }
406 * })
407 * )
408 */
409export function queryCollectionOptions<
410 TExplicit extends object = object,
411 TSchema extends StandardSchemaV1 = never,
412 TQueryFn extends (
413 context: QueryFunctionContext<any>
414 ) => Promise<Array<any>> = (
415 context: QueryFunctionContext<any>
416 ) => Promise<Array<any>>,
417 TError = unknown,
418 TQueryKey extends QueryKey = QueryKey,
419 TKey extends string | number = string | number,
420 TInsertInput extends object = ResolveType<TExplicit, TSchema, TQueryFn>,
421>(
422 config: QueryCollectionConfig<TExplicit, TSchema, TQueryFn, TError, TQueryKey>
423): CollectionConfig<ResolveType<TExplicit, TSchema, TQueryFn>> & {
424 utils: QueryCollectionUtils<
425 ResolveType<TExplicit, TSchema, TQueryFn>,
426 TKey,
427 TInsertInput
428 >
429} {
430 type TItem = ResolveType<TExplicit, TSchema, TQueryFn>
431​
432 const {
433 queryKey,
434 queryFn,
435 queryClient,
436 enabled,
437 refetchInterval,
438 retry,
439 retryDelay,
440 staleTime,
441 getKey,
442 onInsert,
443 onUpdate,
444 onDelete,
445 meta,
446 ...baseCollectionConfig
447 } = config
448​
449 // Validate required parameters
450​
451 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
452 if (!queryKey) {
453 throw new QueryKeyRequiredError()
454 }
455 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
456 if (!queryFn) {
457 throw new QueryFnRequiredError()
458 }
459​
460 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
461 if (!queryClient) {
462 throw new QueryClientRequiredError()
463 }
464​
465 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
466 if (!getKey) {
467 throw new GetKeyRequiredError()
468 }
469​
470 const internalSync: SyncConfig<TItem>[`sync`] = (params) => {
471 const { begin, write, commit, markReady, collection } = params
472​
473 const observerOptions: QueryObserverOptions<
474 Array<TItem>,
475 TError,
476 Array<TItem>,
477 Array<TItem>,
478 TQueryKey
479 > = {
480 queryKey: queryKey,
481 queryFn: queryFn,
482 meta: meta,
483 enabled: enabled,
484 refetchInterval: refetchInterval,
485 retry: retry,
486 retryDelay: retryDelay,
487 staleTime: staleTime,
488 structuralSharing: true,
489 notifyOnChangeProps: `all`,
490 }
491​
492 const localObserver = new QueryObserver<
493 Array<TItem>,
494 TError,
495 Array<TItem>,
496 Array<TItem>,
497 TQueryKey
498 >(queryClient, observerOptions)
499​
500 type UpdateHandler = Parameters<typeof localObserver.subscribe>[0]
501 const handleUpdate: UpdateHandler = (result) => {
502 if (result.isSuccess) {
503 const newItemsArray = result.data
504​
505 if (
506 !Array.isArray(newItemsArray) ||
507 newItemsArray.some((item) => typeof item !== `object`)
508 ) {
509 console.error(
510 `[QueryCollection] queryFn did not return an array of objects. Skipping update.`,
511 newItemsArray
512 )
513 return
514 }
515​
516 const currentSyncedItems = new Map(collection.syncedData)
517 const newItemsMap = new Map<string | number, TItem>()
518 newItemsArray.forEach((item) => {
519 const key = getKey(item)
520 newItemsMap.set(key, item)
521 })
522​
523 begin()
524​
525 // Helper function for shallow equality check of objects
526 const shallowEqual = (
527 obj1: Record<string, any>,
528 obj2: Record<string, any>
529 ): boolean => {
530 // Get all keys from both objects
531 const keys1 = Object.keys(obj1)
532 const keys2 = Object.keys(obj2)
533​
534 // If number of keys is different, objects are not equal
535 if (keys1.length !== keys2.length) return false
536​
537 // Check if all keys in obj1 have the same values in obj2
538 return keys1.every((key) => {
539 // Skip comparing functions and complex objects deeply
540 if (typeof obj1[key] === `function`) return true
541 return obj1[key] === obj2[key]
542 })
543 }
544​
545 currentSyncedItems.forEach((oldItem, key) => {
546 const newItem = newItemsMap.get(key)
547 if (!newItem) {
548 write({ type: `delete`, value: oldItem })
549 } else if (
550 !shallowEqual(
551 oldItem as Record<string, any>,
552 newItem as Record<string, any>
553 )
554 ) {
555 // Only update if there are actual differences in the properties
556 write({ type: `update`, value: newItem })
557 }
558 })
559​
560 newItemsMap.forEach((newItem, key) => {
561 if (!currentSyncedItems.has(key)) {
562 write({ type: `insert`, value: newItem })
563 }
564 })
565​
566 commit()
567​
568 // Mark collection as ready after first successful query result
569 markReady()
570 } else if (result.isError) {
571 console.error(
572 `[QueryCollection] Error observing query ${String(queryKey)}:`,
573 result.error
574 )
575​
576 // Mark collection as ready even on error to avoid blocking apps
577 markReady()
578 }
579 }
580​
581 const actualUnsubscribeFn = localObserver.subscribe(handleUpdate)
582​
583 // Ensure we process any existing query data (QueryObserver doesn't invoke its callback automatically with initial
584 // state)
585 handleUpdate(localObserver.getCurrentResult())
586​
587 return async () => {
588 actualUnsubscribeFn()
589 await queryClient.cancelQueries({ queryKey })
590 queryClient.removeQueries({ queryKey })
591 }
592 }
593​
594 /**
595 * Refetch the query data
596 * @returns Promise that resolves when the refetch is complete
597 */
598 const refetch: RefetchFn = async (): Promise<void> => {
599 return queryClient.refetchQueries({
600 queryKey: queryKey,
601 })
602 }
603​
604 // Create write context for manual write operations
605 let writeContext: {
606 collection: any
607 queryClient: QueryClient
608 queryKey: Array<unknown>
609 getKey: (item: TItem) => TKey
610 begin: () => void
611 write: (message: Omit<ChangeMessage<TItem>, `key`>) => void
612 commit: () => void
613 } | null = null
614​
615 // Enhanced internalSync that captures write functions for manual use
616 const enhancedInternalSync: SyncConfig<TItem>[`sync`] = (params) => {
617 const { begin, write, commit, collection } = params
618​
619 // Store references for manual write operations
620 writeContext = {
621 collection,
622 queryClient,
623 queryKey: queryKey as unknown as Array<unknown>,
624 getKey: getKey as (item: TItem) => TKey,
625 begin,
626 write,
627 commit,
628 }
629​
630 // Call the original internalSync logic
631 return internalSync(params)
632 }
633​
634 // Create write utils using the manual-sync module
635 const writeUtils = createWriteUtils<TItem, TKey, TInsertInput>(
636 () => writeContext
637 )
638​
639 // Create wrapper handlers for direct persistence operations that handle refetching
640 const wrappedOnInsert = onInsert
641 ? async (params: InsertMutationFnParams<TItem>) => {
642 const handlerResult = (await onInsert(params)) ?? {}
643 const shouldRefetch =
644 (handlerResult as { refetch?: boolean }).refetch !== false
645​
646 if (shouldRefetch) {
647 await refetch()
648 }
649​
650 return handlerResult
651 }
652 : undefined
653​
654 const wrappedOnUpdate = onUpdate
655 ? async (params: UpdateMutationFnParams<TItem>) => {
656 const handlerResult = (await onUpdate(params)) ?? {}
657 const shouldRefetch =
658 (handlerResult as { refetch?: boolean }).refetch !== false
659​
660 if (shouldRefetch) {
661 await refetch()
662 }
663​
664 return handlerResult
665 }
666 : undefined
667​
668 const wrappedOnDelete = onDelete
669 ? async (params: DeleteMutationFnParams<TItem>) => {
670 const handlerResult = (await onDelete(params)) ?? {}
671 const shouldRefetch =
672 (handlerResult as { refetch?: boolean }).refetch !== false
673​
674 if (shouldRefetch) {
675 await refetch()
676 }
677​
678 return handlerResult
679 }
680 : undefined
681​
682 return {
683 ...baseCollectionConfig,
684 getKey,
685 sync: { sync: enhancedInternalSync },
686 onInsert: wrappedOnInsert,
687 onUpdate: wrappedOnUpdate,
688 onDelete: wrappedOnDelete,
689 utils: {
690 refetch,
691 ...writeUtils,
692 },
693 }