From b6912261c81a95ee4e23785eb441c8b5184572ea Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Fri, 6 Jun 2025 11:45:50 -0600 Subject: [PATCH 1/5] Switch to Collection options factories instead of extending the Collection class This refactors ElectricCollection and QueryCollection into factory functions (electricCollectionOptions and queryCollectionOptions) that return standard CollectionConfig objects and utility functions. Also adds a createCollection function to standardize collection instantiation. --- examples/react/todo/src/App.tsx | 74 ++-- packages/db-collections/src/electric.ts | 109 +++--- packages/db-collections/src/index.ts | 9 +- packages/db-collections/src/query.ts | 342 +++++++++--------- .../db-collections/tests/electric.test.ts | 33 +- packages/db-collections/tests/query.test.ts | 34 +- packages/db/src/collection.ts | 26 +- 7 files changed, 343 insertions(+), 284 deletions(-) diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index 03a321e0ae..5e63f1fcbc 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -1,16 +1,17 @@ import React, { useState } from "react" -import { useLiveQuery, useOptimisticMutation } from "@tanstack/react-db" import { - createElectricCollection, - createQueryCollection, + collectionsStore, + createCollection, + useLiveQuery, + useOptimisticMutation, +} from "@tanstack/react-db" +import { + electricCollectionOptions, + queryCollectionOptions, } from "@tanstack/db-collections" // import { DevTools } from "./DevTools" import { QueryClient } from "@tanstack/query-core" import { updateConfigSchema, updateTodoSchema } from "./db/validation" -import type { - ElectricCollection, - QueryCollection, -} from "@tanstack/db-collections" import type { Collection, PendingMutation } from "@tanstack/react-db" import type { UpdateConfig, UpdateTodo } from "./db/validation" import type { FormEvent } from "react" @@ -129,7 +130,9 @@ enum CollectionType { // Create a query client for query collections const queryClient = new QueryClient() +// Cache for collections and their utility functions const collectionsCache = new Map() +const utilityFunctionsCache = new Map() // Function to create the appropriate todo collection based on type const createTodoCollection = (type: CollectionType) => { if (collectionsCache.has(`todo`)) { @@ -137,7 +140,7 @@ const createTodoCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - newCollection = createElectricCollection({ + const config = { id: `todos`, shapeOptions: { url: `http://localhost:3003/v1/shape`, @@ -149,12 +152,15 @@ const createTodoCollection = (type: CollectionType) => { timestamptz: (date: string) => new Date(date), }, }, - getId: (item) => item.id, + getId: (item: UpdateTodo) => item.id, schema: updateTodoSchema, - }) + } + const { collectionOptions, awaitTxId } = electricCollectionOptions(config) + newCollection = createCollection(collectionOptions) + utilityFunctionsCache.set(`${config.id}`, awaitTxId) } else { // Query collection using our API helper - newCollection = createQueryCollection({ + const config = { id: `todos`, queryKey: [`todos`], refetchInterval: 3000, @@ -167,10 +173,13 @@ const createTodoCollection = (type: CollectionType) => { updated_at: todo.updated_at ? new Date(todo.updated_at) : undefined, })) }, - getId: (item) => String(item.id), + getId: (item: UpdateTodo) => String(item.id), schema: updateTodoSchema, queryClient, - }) + } + const { collectionOptions, refetch } = queryCollectionOptions(config) + newCollection = createCollection(collectionOptions) + utilityFunctionsCache.set(`${config.id}`, refetch) } collectionsCache.set(`todo`, newCollection) return newCollection @@ -184,7 +193,7 @@ const createConfigCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - newCollection = createElectricCollection({ + const config = { id: `config`, shapeOptions: { url: `http://localhost:3003/v1/shape`, @@ -198,12 +207,15 @@ const createConfigCollection = (type: CollectionType) => { }, }, }, - getId: (item) => item.id, + getId: (item: UpdateConfig) => item.id, schema: updateConfigSchema, - }) + } + const { collectionOptions, awaitTxId } = electricCollectionOptions(config) + newCollection = createCollection(collectionOptions) + utilityFunctionsCache.set(`${config.id}`, awaitTxId) } else { // Query collection using our API helper - newCollection = createQueryCollection({ + const config = { id: `config`, queryKey: [`config`], refetchInterval: 3000, @@ -220,10 +232,13 @@ const createConfigCollection = (type: CollectionType) => { : undefined, })) }, - getId: (item) => item.id, + getId: (item: UpdateConfig) => item.id, schema: updateConfigSchema, queryClient, - }) + } + const { collectionOptions, refetch } = queryCollectionOptions(config) + newCollection = createCollection(collectionOptions) + utilityFunctionsCache.set(`${config.id}`, refetch) } collectionsCache.set(`config`, newCollection) return newCollection @@ -236,12 +251,23 @@ async function collectionSync( mutation: PendingMutation, txid: number ) { + // Get the collection ID from the mutation + const collectionId = mutation.collection.id + + console.log({ collectionId }) if (type === CollectionType.Query) { - await (mutation.collection as QueryCollection).refetch() + // Get the refetch function from the cache + const refetch = utilityFunctionsCache.get(`${collectionId}`) + console.log({ refetch, utilityFunctionsCache }) + if (refetch) { + await refetch() + } } else { - await (mutation.collection as ElectricCollection).awaitTxId( - txid - ) + // Get the awaitTxId function from the cache + const awaitTxId = utilityFunctionsCache.get(`${collectionId}`) + if (awaitTxId) { + await awaitTxId(txid) + } } } @@ -299,7 +325,7 @@ export default function App() { ) await Promise.all( txids.map(async (txid, i) => { - const mutation = transaction.mutations[i] + const mutation = transaction.mutations[i]! return await collectionSync(collectionType, mutation, txid) }) ) diff --git a/packages/db-collections/src/electric.ts b/packages/db-collections/src/electric.ts index dea17239c6..4b95c38a40 100644 --- a/packages/db-collections/src/electric.ts +++ b/packages/db-collections/src/electric.ts @@ -4,7 +4,6 @@ import { isControlMessage, } from "@electric-sql/client" import { Store } from "@tanstack/store" -import { Collection } from "@tanstack/db" import type { CollectionConfig, SyncConfig } from "@tanstack/db" import type { ControlMessage, @@ -14,34 +13,56 @@ import type { } from "@electric-sql/client" /** - * Configuration interface for ElectricCollection + * Configuration interface for Electric collection options */ -export interface ElectricCollectionConfig> - extends Omit, `sync`> { +export interface ElectricCollectionConfig> { /** * Configuration options for the ElectricSQL ShapeStream */ shapeOptions: ShapeStreamOptions + + /** + * All standard Collection configuration properties + */ + id?: string + schema?: CollectionConfig[`schema`] + getId: CollectionConfig[`getId`] + sync?: CollectionConfig[`sync`] } -/** - * Specialized Collection class for ElectricSQL integration - */ -export class ElectricCollection< - T extends Row = Record, -> extends Collection { - private seenTxids: Store> - - constructor(config: ElectricCollectionConfig) { - const seenTxids = new Store>(new Set([Math.random()])) - const sync = createElectricSync(config.shapeOptions, { - seenTxids, - }) +function isUpToDateMessage = Row>( + message: Message +): message is ControlMessage & { up_to_date: true } { + return isControlMessage(message) && message.headers.control === `up-to-date` +} - super({ ...config, sync }) +// Check if a message contains txids in its headers +function hasTxids = Row>( + message: Message +): message is Message & { headers: { txids?: Array } } { + return ( + `headers` in message && + `txids` in message.headers && + Array.isArray(message.headers.txids) + ) +} - this.seenTxids = seenTxids - } +/** + * Creates Electric collection options for use with a standard Collection + * + * @param config - Configuration options for the Electric collection + * @returns Object containing collection options and utility functions + */ +export function electricCollectionOptions>( + config: ElectricCollectionConfig +): { + collectionOptions: CollectionConfig + awaitTxId: (txId: number, timeout?: number) => Promise +} { + const seenTxids = new Store>(new Set([Math.random()])) + const sync = createElectricSync(config.shapeOptions, { + seenTxids, + }) /** * Wait for a specific transaction ID to be synced @@ -49,8 +70,8 @@ export class ElectricCollection< * @param timeout Optional timeout in milliseconds (defaults to 30000ms) * @returns Promise that resolves when the txId is synced */ - async awaitTxId(txId: number, timeout = 30000): Promise { - const hasTxid = this.seenTxids.state.has(txId) + const awaitTxId = async (txId: number, timeout = 30000): Promise => { + const hasTxid = seenTxids.state.has(txId) if (hasTxid) return true return new Promise((resolve, reject) => { @@ -59,8 +80,8 @@ export class ElectricCollection< reject(new Error(`Timeout waiting for txId: ${txId}`)) }, timeout) - const unsubscribe = this.seenTxids.subscribe(() => { - if (this.seenTxids.state.has(txId)) { + const unsubscribe = seenTxids.subscribe(() => { + if (seenTxids.state.has(txId)) { clearTimeout(timeoutId) unsubscribe() resolve(true) @@ -68,39 +89,17 @@ export class ElectricCollection< }) }) } -} - -function isUpToDateMessage = Row>( - message: Message -): message is ControlMessage & { up_to_date: true } { - return isControlMessage(message) && message.headers.control === `up-to-date` -} -// Check if a message contains txids in its headers -function hasTxids = Row>( - message: Message -): message is Message & { headers: { txids?: Array } } { - return ( - `headers` in message && - `txids` in message.headers && - Array.isArray(message.headers.txids) - ) -} + // Extract standard Collection config properties + const { shapeOptions, ...restConfig } = config -/** - * Creates an ElectricSQL sync configuration - * - * @param shapeOptions - Configuration options for the ShapeStream - * @param options - Options for the ElectricSync configuration - * @returns ElectricSync configuration - */ -/** - * Create a new ElectricCollection instance - */ -export function createElectricCollection>( - config: ElectricCollectionConfig -): ElectricCollection { - return new ElectricCollection(config) + return { + collectionOptions: { + ...restConfig, + sync, + }, + awaitTxId, + } } /** diff --git a/packages/db-collections/src/index.ts b/packages/db-collections/src/index.ts index 4e90ac87d9..475a49dac1 100644 --- a/packages/db-collections/src/index.ts +++ b/packages/db-collections/src/index.ts @@ -1,10 +1,5 @@ export { - ElectricCollection, - createElectricCollection, + electricCollectionOptions, type ElectricCollectionConfig, } from "./electric" -export { - QueryCollection, - createQueryCollection, - type QueryCollectionConfig, -} from "./query" +export { queryCollectionOptions, type QueryCollectionConfig } from "./query" diff --git a/packages/db-collections/src/query.ts b/packages/db-collections/src/query.ts index b96e4304f5..e594e81a39 100644 --- a/packages/db-collections/src/query.ts +++ b/packages/db-collections/src/query.ts @@ -1,4 +1,3 @@ -import { Collection } from "@tanstack/db" import { QueryObserver } from "@tanstack/query-core" import type { QueryClient, @@ -12,11 +11,12 @@ export interface QueryCollectionConfig< TItem extends object, TError = unknown, TQueryKey extends QueryKey = QueryKey, -> extends Omit, `sync`> { +> { queryKey: TQueryKey queryFn: (context: QueryFunctionContext) => Promise> - getId: (item: TItem) => string + queryClient: QueryClient + // Query-specific options enabled?: boolean refetchInterval?: QueryObserverOptions< Array, @@ -46,201 +46,209 @@ export interface QueryCollectionConfig< Array, TQueryKey >[`staleTime`] - queryClient: QueryClient + + // Standard Collection configuration properties + id?: string + getId: CollectionConfig[`getId`] + schema?: CollectionConfig[`schema`] + sync?: CollectionConfig[`sync`] } -export class QueryCollection< +/** + * Creates query collection options for use with a standard Collection + * + * @param config - Configuration options for the Query collection + * @returns Object containing collection options and utility functions + */ +export function queryCollectionOptions< TItem extends object, TError = unknown, TQueryKey extends QueryKey = QueryKey, -> extends Collection { - public readonly queryConfig: QueryCollectionConfig - private queryClient: QueryClient - - constructor(config: QueryCollectionConfig) { - const { - queryKey, - queryFn, - queryClient, - enabled, - refetchInterval, - retry, - retryDelay, - staleTime, - ...baseCollectionConfig - } = config - - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (!queryKey) - throw new Error(`[QueryCollection] queryKey must be provided.`) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (!queryFn) throw new Error(`[QueryCollection] queryFn must be provided.`) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (!queryClient) - throw new Error(`[QueryCollection] queryClient must be provided.`) - // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition - if (!baseCollectionConfig.getId) { - throw new Error(`[QueryCollection] getId must be provided.`) - } - - const getIdFn = baseCollectionConfig.getId +>( + config: QueryCollectionConfig +): { + collectionOptions: CollectionConfig + refetch: () => Promise +} { + const { + queryKey, + queryFn, + queryClient, + enabled, + refetchInterval, + retry, + retryDelay, + staleTime, + getId, + ...baseCollectionConfig + } = config + + // Validate required parameters + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!queryKey) { + throw new Error(`[QueryCollection] queryKey must be provided.`) + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!queryFn) { + throw new Error(`[QueryCollection] queryFn must be provided.`) + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!queryClient) { + throw new Error(`[QueryCollection] queryClient must be provided.`) + } + // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition + if (!getId) { + throw new Error(`[QueryCollection] getId must be provided.`) + } - const internalSync: SyncConfig[`sync`] = (params) => { - const { begin, write, commit, collection } = params + const internalSync: SyncConfig[`sync`] = (params) => { + const { begin, write, commit, collection } = params + + const observerOptions: QueryObserverOptions< + Array, + TError, + Array, + Array, + TQueryKey + > = { + queryKey: queryKey, + queryFn: queryFn, + enabled: enabled, + refetchInterval: refetchInterval, + retry: retry, + retryDelay: retryDelay, + staleTime: staleTime, + structuralSharing: true, + notifyOnChangeProps: `all`, + } - const observerOptions: QueryObserverOptions< - Array, - TError, - Array, - Array, - TQueryKey - > = { - queryKey: queryKey, - queryFn: queryFn, - enabled: enabled, - refetchInterval: refetchInterval, - retry: retry, - retryDelay: retryDelay, - staleTime: staleTime, - structuralSharing: true, - notifyOnChangeProps: `all`, - } + const localObserver = new QueryObserver< + Array, + TError, + Array, + Array, + TQueryKey + >(queryClient, observerOptions) + + const actualUnsubscribeFn = localObserver.subscribe((result) => { + if (result.isSuccess) { + const newItemsArray = result.data + + if ( + !Array.isArray(newItemsArray) || + newItemsArray.some((item) => typeof item !== `object`) + ) { + console.error( + `[QueryCollection] queryFn did not return an array of objects. Skipping update.`, + newItemsArray + ) + return + } - const localObserver = new QueryObserver< - Array, - TError, - Array, - Array, - TQueryKey - >(queryClient, observerOptions) - - const actualUnsubscribeFn = localObserver.subscribe((result) => { - if (result.isSuccess) { - const newItemsArray = result.data - - if ( - !Array.isArray(newItemsArray) || - newItemsArray.some((item) => typeof item !== `object`) - ) { + const currentSyncedItems = new Map(collection.syncedData.state) + const newItemsMap = new Map() + newItemsArray.forEach((item) => { + try { + const key = getId(item) + newItemsMap.set(key, item) + } catch (e) { console.error( - `[QueryCollection] queryFn did not return an array of objects. Skipping update.`, - newItemsArray + `[QueryCollection] Error getting primary key for an item. Skipping item:`, + item, + e ) - return } - - const currentSyncedItems = new Map(collection.syncedData.state) - const newItemsMap = new Map() - newItemsArray.forEach((item) => { - try { - const key = getIdFn(item) - newItemsMap.set(key, item) - } catch (e) { - console.error( - `[QueryCollection] Error getting primary key for an item. Skipping item:`, - item, - e - ) - } - }) - - begin() - - // Helper function for shallow equality check of objects - const shallowEqual = ( - obj1: Record, - obj2: Record - ): boolean => { - // Get all keys from both objects - const keys1 = Object.keys(obj1) - const keys2 = Object.keys(obj2) - - // If number of keys is different, objects are not equal - if (keys1.length !== keys2.length) return false - - // Check if all keys in obj1 have the same values in obj2 - return keys1.every((key) => { - // Skip comparing functions and complex objects deeply - if (typeof obj1[key] === `function`) return true - if (typeof obj1[key] === `object` && obj1[key] !== null) { - // For nested objects, just compare references - // A more robust solution might do recursive shallow comparison - // or let users provide a custom equality function - return obj1[key] === obj2[key] - } + }) + + begin() + + // Helper function for shallow equality check of objects + const shallowEqual = ( + obj1: Record, + obj2: Record + ): boolean => { + // Get all keys from both objects + const keys1 = Object.keys(obj1) + const keys2 = Object.keys(obj2) + + // If number of keys is different, objects are not equal + if (keys1.length !== keys2.length) return false + + // Check if all keys in obj1 have the same values in obj2 + return keys1.every((key) => { + // Skip comparing functions and complex objects deeply + if (typeof obj1[key] === `function`) return true + if (typeof obj1[key] === `object` && obj1[key] !== null) { + // For nested objects, just compare references + // A more robust solution might do recursive shallow comparison + // or let users provide a custom equality function return obj1[key] === obj2[key] - }) - } - - currentSyncedItems.forEach((oldItem, key) => { - const newItem = newItemsMap.get(key) - if (!newItem) { - write({ type: `delete`, value: oldItem }) - } else if ( - !shallowEqual( - oldItem as Record, - newItem as Record - ) - ) { - // Only update if there are actual differences in the properties - write({ type: `update`, value: newItem }) } + return obj1[key] === obj2[key] }) - - newItemsMap.forEach((newItem, key) => { - if (!currentSyncedItems.has(key)) { - write({ type: `insert`, value: newItem }) - } - }) - - commit() - } else if (result.isError) { - console.error( - `[QueryCollection] Error observing query ${String(queryKey)}:`, - result.error - ) } - }) - return actualUnsubscribeFn - } + currentSyncedItems.forEach((oldItem, key) => { + const newItem = newItemsMap.get(key) + if (!newItem) { + write({ type: `delete`, value: oldItem }) + } else if ( + !shallowEqual( + oldItem as Record, + newItem as Record + ) + ) { + // Only update if there are actual differences in the properties + write({ type: `update`, value: newItem }) + } + }) - super({ - ...baseCollectionConfig, - sync: { sync: internalSync }, + newItemsMap.forEach((newItem, key) => { + if (!currentSyncedItems.has(key)) { + write({ type: `insert`, value: newItem }) + } + }) + + commit() + } else if (result.isError) { + console.error( + `[QueryCollection] Error observing query ${String(queryKey)}:`, + result.error + ) + } }) - this.queryConfig = config - this.queryClient = queryClient + return actualUnsubscribeFn } - public async refetch(): Promise { - console.log( - `[QueryCollection] refetch() called for ${String(this.queryConfig.queryKey)}` - ) + /** + * Refetch the query data + * @returns Promise that resolves when the refetch is complete + */ + const refetch = async (): Promise => { + console.log(`[QueryCollection] refetch() called for ${String(queryKey)}`) try { - await this.queryClient.refetchQueries({ - queryKey: this.queryConfig.queryKey, + await queryClient.refetchQueries({ + queryKey: queryKey, }) console.log( - `[QueryCollection] Refetch successful for ${String(this.queryConfig.queryKey)}.` + `[QueryCollection] Refetch successful for ${String(queryKey)}.` ) } catch (error) { console.error( - `[QueryCollection] Error during refetch for ${String(this.queryConfig.queryKey)}:`, + `[QueryCollection] Error during refetch for ${String(queryKey)}:`, error ) throw error } } -} -export function createQueryCollection< - TItem extends object, - TError = unknown, - TQueryKey extends QueryKey = QueryKey, ->( - config: QueryCollectionConfig -): QueryCollection { - return new QueryCollection(config) + return { + collectionOptions: { + ...baseCollectionConfig, + getId, + sync: { sync: internalSync }, + }, + refetch, + } } diff --git a/packages/db-collections/tests/electric.test.ts b/packages/db-collections/tests/electric.test.ts index d744528054..c28a02d19c 100644 --- a/packages/db-collections/tests/electric.test.ts +++ b/packages/db-collections/tests/electric.test.ts @@ -1,7 +1,6 @@ import { beforeEach, describe, expect, it, vi } from "vitest" -import { createTransaction } from "@tanstack/db" -import { createElectricCollection } from "../src/electric" -import type { ElectricCollection } from "../src/electric" +import { Collection, createTransaction } from "@tanstack/db" +import { electricCollectionOptions } from "../src/electric" import type { PendingMutation, Transaction } from "@tanstack/db" import type { Message, Row } from "@electric-sql/client" @@ -20,7 +19,8 @@ vi.mock(`@electric-sql/client`, async () => { }) describe(`Electric Integration`, () => { - let collection: ElectricCollection + let collection: Collection + let awaitTxId: (txId: number, timeout?: number) => Promise let subscriber: (messages: Array>) => void beforeEach(() => { @@ -33,7 +33,7 @@ describe(`Electric Integration`, () => { }) // Create collection with Electric configuration - collection = createElectricCollection({ + const config = { id: `test`, shapeOptions: { url: `http://test-url`, @@ -41,8 +41,13 @@ describe(`Electric Integration`, () => { table: `test_table`, }, }, - getId: (item) => item.id, - }) + getId: (item: Row) => item.id, + } + + const { collectionOptions, awaitTxId: txIdFn } = + electricCollectionOptions(config) + collection = new Collection(collectionOptions) + awaitTxId = txIdFn }) it(`should handle incoming insert messages and commit on up-to-date`, () => { @@ -202,7 +207,7 @@ describe(`Electric Integration`, () => { ]) // The txid should be tracked and awaitTxId should resolve immediately - await expect(collection.awaitTxId(testTxid)).resolves.toBe(true) + await expect(awaitTxId(testTxid)).resolves.toBe(true) }) it(`should handle multiple txids in a single message`, async () => { @@ -225,8 +230,8 @@ describe(`Electric Integration`, () => { ]) // Both txids should be tracked - await expect(collection.awaitTxId(txid1)).resolves.not.toThrow() - await expect(collection.awaitTxId(txid2)).resolves.not.toThrow() + await expect(awaitTxId(txid1)).resolves.not.toThrow() + await expect(awaitTxId(txid2)).resolves.not.toThrow() }) it(`should reject with timeout when waiting for unknown txid`, async () => { @@ -235,7 +240,7 @@ describe(`Electric Integration`, () => { const shortTimeout = 100 // Attempt to await a txid that hasn't been seen with a short timeout - const promise = collection.awaitTxId(unknownTxid, shortTimeout) + const promise = awaitTxId(unknownTxid, shortTimeout) // The promise should reject with a timeout error await expect(promise).rejects.toThrow( @@ -247,7 +252,7 @@ describe(`Electric Integration`, () => { const laterTxid = 1000 // Start waiting for a txid that hasn't arrived yet - const promise = collection.awaitTxId(laterTxid, 1000) + const promise = awaitTxId(laterTxid, 1000) // Send the txid after a short delay setTimeout(() => { @@ -337,7 +342,7 @@ describe(`Electric Integration`, () => { } // Start waiting for the txid - const promise = collection.awaitTxId(txid, 1000) + const promise = awaitTxId(txid, 1000) // Simulate the server sending sync messages after a delay setTimeout(() => { @@ -354,7 +359,7 @@ describe(`Electric Integration`, () => { const tx1 = createTransaction({ mutationFn: testMutationFn }) let transaction = tx1.mutate(() => - collection.insert({ id: 1, name: `Test item 1` }, { key: `item1` }) + collection.insert({ id: 1, name: `Test item 1` }) ) await transaction.isPersisted.promise diff --git a/packages/db-collections/tests/query.test.ts b/packages/db-collections/tests/query.test.ts index a4e4546b40..12c966ea47 100644 --- a/packages/db-collections/tests/query.test.ts +++ b/packages/db-collections/tests/query.test.ts @@ -1,6 +1,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { QueryClient } from "@tanstack/query-core" -import { createQueryCollection } from "../src/query" +import { Collection } from "@tanstack/db" +import { queryCollectionOptions } from "../src/query" import type { QueryCollectionConfig } from "../src/query" interface TestItem { @@ -52,7 +53,8 @@ describe(`QueryCollection`, () => { getId, } - const collection = createQueryCollection(config) + const { collectionOptions } = queryCollectionOptions(config) + const collection = new Collection(collectionOptions) // Wait for the query to complete and collection to update await vi.waitFor( @@ -111,7 +113,8 @@ describe(`QueryCollection`, () => { getId, } - const collection = createQueryCollection(config) + const { collectionOptions, refetch } = queryCollectionOptions(config) + const collection = new Collection(collectionOptions) // Wait for initial data to load await vi.waitFor(() => { @@ -141,7 +144,7 @@ describe(`QueryCollection`, () => { ] // Refetch the query. - await collection.refetch() + await refetch() expect(queryFn).toHaveBeenCalledTimes(2) // Check for update, addition, and removal @@ -160,7 +163,7 @@ describe(`QueryCollection`, () => { currentItems = [...currentItems, item4] // Refetch the query to trigger a refetch. - await collection.refetch() + await refetch() // Verify expected. expect(queryFn).toHaveBeenCalledTimes(3) @@ -178,13 +181,12 @@ describe(`QueryCollection`, () => { .spyOn(console, `error`) .mockImplementation(() => {}) - // First call succeeds, second call fails const queryFn = vi .fn() .mockResolvedValueOnce([initialItem]) .mockRejectedValueOnce(testError) - const collection = createQueryCollection({ + const { collectionOptions, refetch } = queryCollectionOptions({ id: `test`, queryClient, queryKey, @@ -192,6 +194,7 @@ describe(`QueryCollection`, () => { getId, retry: 0, // Disable retries for this test case }) + const collection = new Collection(collectionOptions) // Wait for initial data to load await vi.waitFor(() => { @@ -203,7 +206,7 @@ describe(`QueryCollection`, () => { }) // Trigger an error by refetching - await collection.refetch() + await refetch() // Wait for the error to be logged expect(queryFn).toHaveBeenCalledTimes(2) @@ -233,13 +236,14 @@ describe(`QueryCollection`, () => { // Mock queryFn to return invalid data (not an array of objects) const queryFn = vi.fn().mockResolvedValue(`not an array` as any) - const collection = createQueryCollection({ + const { collectionOptions } = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId, }) + const collection = new Collection(collectionOptions) // Wait for the query to execute await vi.waitFor(() => { @@ -280,13 +284,14 @@ describe(`QueryCollection`, () => { // Spy on console.log to detect when commits happen const consoleSpy = vi.spyOn(console, `log`) - const collection = createQueryCollection({ + const { collectionOptions, refetch } = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId, }) + const collection = new Collection(collectionOptions) // Wait for initial data to load await vi.waitFor(() => { @@ -302,7 +307,7 @@ describe(`QueryCollection`, () => { consoleSpy.mockClear() // Trigger first refetch - should not cause an update due to shallow equality - await collection.refetch() + await refetch() expect(queryFn).toHaveBeenCalledTimes(2) // Verify refetch was logged @@ -325,7 +330,7 @@ describe(`QueryCollection`, () => { consoleSpy.mockClear() // Trigger second refetch - should cause an update due to actual data change - await collection.refetch() + await refetch() expect(queryFn).toHaveBeenCalledTimes(3) // Verify refetch was logged @@ -361,13 +366,14 @@ describe(`QueryCollection`, () => { // Create a spy for the getId function const getIdSpy = vi.fn((item: any) => item.customId) - const collection = createQueryCollection({ + const { collectionOptions, refetch } = queryCollectionOptions({ id: `test`, queryClient, queryKey, queryFn, getId: getIdSpy, }) + const collection = new Collection(collectionOptions) // Wait for initial data to load await vi.waitFor(() => { @@ -403,7 +409,7 @@ describe(`QueryCollection`, () => { queryFn.mockResolvedValueOnce(updatedItems) // Trigger a refetch - await collection.refetch() + await refetch() expect(queryFn).toHaveBeenCalledTimes(2) expect(collection.state.size).toBe(updatedItems.length) diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index e176f798ee..1f9386592b 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -28,6 +28,19 @@ interface PendingSyncedTransaction> { operations: Array> } +/** + * Creates a new Collection instance with the given configuration + * + * @template T - The type of items in the collection + * @param config - Configuration for the collection, including id and sync + * @returns A new Collection instance + */ +export function createCollection>( + config: CollectionConfig +): Collection { + return new Collection(config) +} + /** * Preloads a collection with the given configuration * Returns a promise that resolves once the sync tool has done its first commit (initial sync is finished) @@ -180,7 +193,7 @@ export class Collection> { this.onFirstCommitCallbacks.push(callback) } - public id = crypto.randomUUID() + public id = `` /** * Creates a new Collection instance @@ -188,8 +201,15 @@ export class Collection> { * @param config - Configuration object for the collection * @throws Error if sync config is missing */ - constructor(config?: CollectionConfig) { - if (!config?.sync) { + constructor(config: CollectionConfig) { + if (config.id) { + this.id = config.id + } else { + this.id = crypto.randomUUID() + } + + // eslint-disable-next-line + if (!config.sync) { throw new Error(`Collection requires a sync config`) } From 4b748a2ff78dbc2a9a86b5c4398d3c4aef82f0fb Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Fri, 6 Jun 2025 11:53:26 -0600 Subject: [PATCH 2/5] fix test --- packages/db/src/collection.ts | 4 ++++ packages/db/tests/collection.test.ts | 2 +- 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index 1f9386592b..461b27d0d1 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -202,6 +202,10 @@ export class Collection> { * @throws Error if sync config is missing */ constructor(config: CollectionConfig) { + // eslint-disable-next-line + if (!config) { + throw new Error(`Collection requires a config`) + } if (config.id) { this.id = config.id } else { diff --git a/packages/db/tests/collection.test.ts b/packages/db/tests/collection.test.ts index 532fbdb210..173bbae39b 100644 --- a/packages/db/tests/collection.test.ts +++ b/packages/db/tests/collection.test.ts @@ -12,7 +12,7 @@ import type { describe(`Collection`, () => { it(`should throw if there's no sync config`, () => { - expect(() => new Collection()).toThrow(`Collection requires a sync config`) + expect(() => new Collection()).toThrow(`Collection requires a config`) }) it(`should throw an error when trying to use mutation operations outside of a transaction`, async () => { From c79651d7ad7c0aa107d72717cad9bfd29e563c65 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Fri, 6 Jun 2025 12:03:36 -0600 Subject: [PATCH 3/5] refactor --- examples/react/todo/src/App.tsx | 31 ++++++++++++++----------------- 1 file changed, 14 insertions(+), 17 deletions(-) diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index 5e63f1fcbc..db06da6892 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -140,7 +140,7 @@ const createTodoCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - const config = { + const { collectionOptions, awaitTxId } = electricCollectionOptions({ id: `todos`, shapeOptions: { url: `http://localhost:3003/v1/shape`, @@ -152,15 +152,15 @@ const createTodoCollection = (type: CollectionType) => { timestamptz: (date: string) => new Date(date), }, }, - getId: (item: UpdateTodo) => item.id, + getId: (item) => item.id, schema: updateTodoSchema, - } - const { collectionOptions, awaitTxId } = electricCollectionOptions(config) + }) newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${config.id}`, awaitTxId) + utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId) } else { // Query collection using our API helper - const config = { + + const { collectionOptions, refetch } = queryCollectionOptions({ id: `todos`, queryKey: [`todos`], refetchInterval: 3000, @@ -176,10 +176,9 @@ const createTodoCollection = (type: CollectionType) => { getId: (item: UpdateTodo) => String(item.id), schema: updateTodoSchema, queryClient, - } - const { collectionOptions, refetch } = queryCollectionOptions(config) + }) newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${config.id}`, refetch) + utilityFunctionsCache.set(`${newCollection.id}`, refetch) } collectionsCache.set(`todo`, newCollection) return newCollection @@ -193,7 +192,7 @@ const createConfigCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - const config = { + const { collectionOptions, awaitTxId } = electricCollectionOptions({ id: `config`, shapeOptions: { url: `http://localhost:3003/v1/shape`, @@ -209,13 +208,12 @@ const createConfigCollection = (type: CollectionType) => { }, getId: (item: UpdateConfig) => item.id, schema: updateConfigSchema, - } - const { collectionOptions, awaitTxId } = electricCollectionOptions(config) + }) newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${config.id}`, awaitTxId) + utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId) } else { // Query collection using our API helper - const config = { + const { collectionOptions, refetch } = queryCollectionOptions({ id: `config`, queryKey: [`config`], refetchInterval: 3000, @@ -235,10 +233,9 @@ const createConfigCollection = (type: CollectionType) => { getId: (item: UpdateConfig) => item.id, schema: updateConfigSchema, queryClient, - } - const { collectionOptions, refetch } = queryCollectionOptions(config) + }) newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${config.id}`, refetch) + utilityFunctionsCache.set(`${newCollection.id}`, refetch) } collectionsCache.set(`config`, newCollection) return newCollection From 046c310dacb2d0aa9e5c48debeed82085825a9a2 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Fri, 6 Jun 2025 12:04:18 -0600 Subject: [PATCH 4/5] remove console.log --- examples/react/todo/src/App.tsx | 2 -- 1 file changed, 2 deletions(-) diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index db06da6892..5bc38612a4 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -251,11 +251,9 @@ async function collectionSync( // Get the collection ID from the mutation const collectionId = mutation.collection.id - console.log({ collectionId }) if (type === CollectionType.Query) { // Get the refetch function from the cache const refetch = utilityFunctionsCache.get(`${collectionId}`) - console.log({ refetch, utilityFunctionsCache }) if (refetch) { await refetch() } From 8ac8101a7b66359184906147f13cc363dc998160 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Fri, 6 Jun 2025 12:10:02 -0600 Subject: [PATCH 5/5] Add changeset --- .changeset/smart-points-chew.md | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 .changeset/smart-points-chew.md diff --git a/.changeset/smart-points-chew.md b/.changeset/smart-points-chew.md new file mode 100644 index 0000000000..de2ddc978d --- /dev/null +++ b/.changeset/smart-points-chew.md @@ -0,0 +1,9 @@ +--- +"@tanstack/db-collections": patch +"@tanstack/db-example-react-todo": patch +"@tanstack/db": patch +--- + +Switch to Collection options factories instead of extending the Collection class + +This refactors `ElectricCollection` and `QueryCollection` into factory functions (`electricCollectionOptions` and `queryCollectionOptions`) that return standard `CollectionConfig` objects and utility functions. Also adds a `createCollection` function to standardize collection instantiation.