Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/smart-points-chew.md
Original file line number Diff line number Diff line change
@@ -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.
59 changes: 40 additions & 19 deletions examples/react/todo/src/App.tsx
Original file line number Diff line number Diff line change
@@ -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"
Expand Down Expand Up @@ -129,15 +130,17 @@ 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`)) {
return collectionsCache.get(`todo`)
} else {
let newCollection: Collection
if (type === CollectionType.Electric) {
newCollection = createElectricCollection<UpdateTodo>({
const { collectionOptions, awaitTxId } = electricCollectionOptions({
id: `todos`,
shapeOptions: {
url: `http://localhost:3003/v1/shape`,
Expand All @@ -152,9 +155,12 @@ const createTodoCollection = (type: CollectionType) => {
getId: (item) => item.id,
schema: updateTodoSchema,
})
newCollection = createCollection(collectionOptions)
utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId)
} else {
// Query collection using our API helper
newCollection = createQueryCollection<UpdateTodo>({

const { collectionOptions, refetch } = queryCollectionOptions({
id: `todos`,
queryKey: [`todos`],
refetchInterval: 3000,
Expand All @@ -167,10 +173,12 @@ 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,
})
newCollection = createCollection(collectionOptions)
utilityFunctionsCache.set(`${newCollection.id}`, refetch)
}
collectionsCache.set(`todo`, newCollection)
return newCollection
Expand All @@ -184,7 +192,7 @@ const createConfigCollection = (type: CollectionType) => {
} else {
let newCollection: Collection
if (type === CollectionType.Electric) {
newCollection = createElectricCollection<UpdateConfig>({
const { collectionOptions, awaitTxId } = electricCollectionOptions({
id: `config`,
shapeOptions: {
url: `http://localhost:3003/v1/shape`,
Expand All @@ -198,12 +206,14 @@ const createConfigCollection = (type: CollectionType) => {
},
},
},
getId: (item) => item.id,
getId: (item: UpdateConfig) => item.id,
schema: updateConfigSchema,
})
newCollection = createCollection(collectionOptions)
utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId)
} else {
// Query collection using our API helper
newCollection = createQueryCollection<UpdateConfig>({
const { collectionOptions, refetch } = queryCollectionOptions({
id: `config`,
queryKey: [`config`],
refetchInterval: 3000,
Expand All @@ -220,10 +230,12 @@ const createConfigCollection = (type: CollectionType) => {
: undefined,
}))
},
getId: (item) => item.id,
getId: (item: UpdateConfig) => item.id,
schema: updateConfigSchema,
queryClient,
})
newCollection = createCollection(collectionOptions)
utilityFunctionsCache.set(`${newCollection.id}`, refetch)
}
collectionsCache.set(`config`, newCollection)
return newCollection
Expand All @@ -236,12 +248,21 @@ async function collectionSync(
mutation: PendingMutation,
txid: number
) {
// Get the collection ID from the mutation
const collectionId = mutation.collection.id

if (type === CollectionType.Query) {
await (mutation.collection as QueryCollection<UpdateTodo>).refetch()
// Get the refetch function from the cache
const refetch = utilityFunctionsCache.get(`${collectionId}`)
if (refetch) {
await refetch()
}
} else {
await (mutation.collection as ElectricCollection<UpdateTodo>).awaitTxId(
txid
)
// Get the awaitTxId function from the cache
const awaitTxId = utilityFunctionsCache.get(`${collectionId}`)
if (awaitTxId) {
await awaitTxId(txid)
}
}
}

Expand Down Expand Up @@ -299,7 +320,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)
})
)
Expand Down
109 changes: 54 additions & 55 deletions packages/db-collections/src/electric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -14,43 +13,65 @@ import type {
} from "@electric-sql/client"

/**
* Configuration interface for ElectricCollection
* Configuration interface for Electric collection options
*/
export interface ElectricCollectionConfig<T extends Row<unknown>>
extends Omit<CollectionConfig<T>, `sync`> {
export interface ElectricCollectionConfig<T extends Row<unknown>> {
/**
* Configuration options for the ElectricSQL ShapeStream
*/
shapeOptions: ShapeStreamOptions

/**
* All standard Collection configuration properties
*/
id?: string
schema?: CollectionConfig<T>[`schema`]
getId: CollectionConfig<T>[`getId`]
sync?: CollectionConfig<T>[`sync`]
}

/**
* Specialized Collection class for ElectricSQL integration
*/
export class ElectricCollection<
T extends Row<unknown> = Record<string, unknown>,
> extends Collection<T> {
private seenTxids: Store<Set<number>>

constructor(config: ElectricCollectionConfig<T>) {
const seenTxids = new Store<Set<number>>(new Set([Math.random()]))
const sync = createElectricSync<T>(config.shapeOptions, {
seenTxids,
})
function isUpToDateMessage<T extends Row<unknown> = Row>(
message: Message<T>
): 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<T extends Row<unknown> = Row>(
message: Message<T>
): message is Message<T> & { headers: { txids?: Array<number> } } {
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<T extends Row<unknown>>(
config: ElectricCollectionConfig<T>
): {
collectionOptions: CollectionConfig<T>
awaitTxId: (txId: number, timeout?: number) => Promise<boolean>
} {
const seenTxids = new Store<Set<number>>(new Set([Math.random()]))
const sync = createElectricSync<T>(config.shapeOptions, {
seenTxids,
})

/**
* Wait for a specific transaction ID to be synced
* @param txId The transaction ID to wait for
* @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<boolean> {
const hasTxid = this.seenTxids.state.has(txId)
const awaitTxId = async (txId: number, timeout = 30000): Promise<boolean> => {
const hasTxid = seenTxids.state.has(txId)
if (hasTxid) return true

return new Promise((resolve, reject) => {
Expand All @@ -59,48 +80,26 @@ 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)
}
})
})
}
}

function isUpToDateMessage<T extends Row<unknown> = Row>(
message: Message<T>
): 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<T extends Row<unknown> = Row>(
message: Message<T>
): message is Message<T> & { headers: { txids?: Array<number> } } {
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<T extends Row<unknown>>(
config: ElectricCollectionConfig<T>
): ElectricCollection<T> {
return new ElectricCollection(config)
return {
collectionOptions: {
...restConfig,
sync,
},
awaitTxId,
}
}

/**
Expand Down
9 changes: 2 additions & 7 deletions packages/db-collections/src/index.ts
Original file line number Diff line number Diff line change
@@ -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"
Loading