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
21 changes: 21 additions & 0 deletions .changeset/angry-chairs-tan.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
---
"@tanstack/db-collections": patch
"@tanstack/react-db": patch
"@tanstack/vue-db": patch
"@tanstack/db": patch
---

Expose utilities on collection instances

Implemented a utility exposure pattern for TanStack DB collections that allows utility functions to be passed as part of collection options and exposes them under a `.utils` namespace, with full TypeScript typing.

- Refactored `createCollection` in packages/db/src/collection.ts to accept options with utilities directly
- Added `utils` property to CollectionImpl
- Added TypeScript types for utility functions and utility records
- Changed Collection from a class to a type, updating all usages to use createCollection() instead
- Updated Electric/Query implementations

- Utilities are now ergonomically accessible under `.utils`
- Full TypeScript typing is preserved for both collection data and utilities
- API is clean and straightforward - users can call `createCollection(optionsCreator(config))` directly
- Zero-boilerplate TypeScript pattern that infers utility types automatically
8 changes: 4 additions & 4 deletions docs/overview.md
Original file line number Diff line number Diff line change
Expand Up @@ -200,7 +200,7 @@ export const todoCollection = createCollection<Todo>(electricCollectionOptions({
},
getId: (item) => item.id,
schema: todoSchema
}).options)
}))
```

The Electric collection requires two Electric-specific options:
Expand Down Expand Up @@ -230,7 +230,7 @@ export const myPendingTodos = createCollection<Todo>(electricCollectionOptions({
},
getId: (item) => item.id,
schema: todoSchema
}).options)
}))
```

> [!TIP]
Expand Down Expand Up @@ -524,7 +524,7 @@ const todoCollection = createCollection<Todo>(queryCollectionOptions({
await api.todos.create(newTodo)
}
// also add onUpdate, onDelete as needed.
}).options)
}))
const listCollection = createCollection<TodoList>(queryCollectionOptions({
queryKey: ["todo-lists"],
queryFn: async () => fetch("/api/todo-lists"),
Expand All @@ -537,7 +537,7 @@ const listCollection = createCollection<TodoList>(queryCollectionOptions({
await api.todoLists.create(newTodo)
}
// also add onUpdate, onDelete as needed.
}).options)
}))

const Todos = () => {
// Read the data using live queries. Here we show a live
Expand Down
8 changes: 4 additions & 4 deletions examples/react/todo/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -179,7 +179,7 @@ const createTodoCollection = (type: CollectionType) => {

return { txid: String(txids[0].txid) }
},
}).options
})
)
} else {
// Query collection using our API helper
Expand Down Expand Up @@ -224,7 +224,7 @@ const createTodoCollection = (type: CollectionType) => {
})
)
},
}).options
})
)
}
collectionsCache.set(`todo`, newCollection)
Expand Down Expand Up @@ -275,7 +275,7 @@ const createConfigCollection = (type: CollectionType) => {

return { txid: String(txids[0]) }
},
}).options
})
)
} else {
// Query collection using our API helper
Expand Down Expand Up @@ -319,7 +319,7 @@ const createConfigCollection = (type: CollectionType) => {

return { txid: String(txids[0]) }
},
}).options
})
)
}
collectionsCache.set(`config`, newCollection)
Expand Down
39 changes: 26 additions & 13 deletions packages/db-collections/src/electric.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import type {
CollectionConfig,
MutationFnParams,
SyncConfig,
UtilsRecord,
} from "@tanstack/db"
import type {
ControlMessage,
Expand Down Expand Up @@ -75,18 +76,27 @@ function hasTxids<T extends Row<unknown> = Row>(
)
}

/**
* Type for the awaitTxId utility function
*/
export type AwaitTxIdFn = (txId: string, timeout?: number) => Promise<boolean>

/**
* Electric collection utilities type
*/
export interface ElectricCollectionUtils extends UtilsRecord {
awaitTxId: AwaitTxIdFn
}

/**
* 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
* @returns Collection options with utilities
*/
export function electricCollectionOptions<T extends Row<unknown>>(
config: ElectricCollectionConfig<T>
): {
options: CollectionConfig<T>
awaitTxId: (txId: string, timeout?: number) => Promise<boolean>
} {
) {
const seenTxids = new Store<Set<string>>(new Set([`${Math.random()}`]))
const sync = createElectricSync<T>(config.shapeOptions, {
seenTxids,
Expand All @@ -98,7 +108,10 @@ export function electricCollectionOptions<T extends Row<unknown>>(
* @param timeout Optional timeout in milliseconds (defaults to 30000ms)
* @returns Promise that resolves when the txId is synced
*/
const awaitTxId = async (txId: string, timeout = 30000): Promise<boolean> => {
const awaitTxId: AwaitTxIdFn = async (
txId: string,
timeout = 30000
): Promise<boolean> => {
const hasTxid = seenTxids.state.has(txId)
if (hasTxid) return true

Expand Down Expand Up @@ -171,14 +184,14 @@ export function electricCollectionOptions<T extends Row<unknown>>(
const { shapeOptions, onInsert, onUpdate, onDelete, ...restConfig } = config

return {
options: {
...restConfig,
sync,
onInsert: wrappedOnInsert,
onUpdate: wrappedOnUpdate,
onDelete: wrappedOnDelete,
...restConfig,
sync,
onInsert: wrappedOnInsert,
onUpdate: wrappedOnUpdate,
onDelete: wrappedOnDelete,
utils: {
awaitTxId,
},
awaitTxId,
}
}

Expand Down
38 changes: 24 additions & 14 deletions packages/db-collections/src/query.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import type {
CollectionConfig,
MutationFnParams,
SyncConfig,
UtilsRecord,
} from "@tanstack/db"

export interface QueryCollectionConfig<
Expand Down Expand Up @@ -80,22 +81,31 @@ export interface QueryCollectionConfig<
onDelete?: CollectionConfig<TItem>[`onDelete`]
}

/**
* Type for the refetch utility function
*/
export type RefetchFn = () => Promise<void>

/**
* Query collection utilities type
*/
export interface QueryCollectionUtils extends UtilsRecord {
refetch: RefetchFn
}

/**
* 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
* @returns Collection options with utilities
*/
export function queryCollectionOptions<
TItem extends object,
TError = unknown,
TQueryKey extends QueryKey = QueryKey,
>(
config: QueryCollectionConfig<TItem, TError, TQueryKey>
): {
options: CollectionConfig<TItem>
refetch: () => Promise<void>
} {
): CollectionConfig<TItem> & { utils: QueryCollectionUtils } {
const {
queryKey,
queryFn,
Expand Down Expand Up @@ -254,7 +264,7 @@ export function queryCollectionOptions<
* Refetch the query data
* @returns Promise that resolves when the refetch is complete
*/
const refetch = async (): Promise<void> => {
const refetch: RefetchFn = async (): Promise<void> => {
console.log(`[QueryCollection] refetch() called for ${String(queryKey)}`)
try {
await queryClient.refetchQueries({
Expand Down Expand Up @@ -316,14 +326,14 @@ export function queryCollectionOptions<
: undefined

return {
options: {
...baseCollectionConfig,
getId,
sync: { sync: internalSync },
onInsert: wrappedOnInsert,
onUpdate: wrappedOnUpdate,
onDelete: wrappedOnDelete,
...baseCollectionConfig,
getId,
sync: { sync: internalSync },
onInsert: wrappedOnInsert,
onUpdate: wrappedOnUpdate,
onDelete: wrappedOnDelete,
utils: {
refetch,
},
refetch,
}
}
34 changes: 18 additions & 16 deletions packages/db-collections/tests/electric.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,9 @@
import { beforeEach, describe, expect, it, vi } from "vitest"
import { Collection, createTransaction } from "@tanstack/db"
import { createCollection, createTransaction } from "@tanstack/db"
import { electricCollectionOptions } from "../src/electric"
import type { ElectricCollectionUtils } from "../src/electric"
import type {
Collection,
MutationFnParams,
PendingMutation,
Transaction,
Expand All @@ -23,8 +25,7 @@ vi.mock(`@electric-sql/client`, async () => {
})

describe(`Electric Integration`, () => {
let collection: Collection<Row>
let awaitTxId: (txId: string, timeout?: number) => Promise<boolean>
let collection: Collection<Row, ElectricCollectionUtils>
let subscriber: (messages: Array<Message<Row>>) => void

beforeEach(() => {
Expand All @@ -48,9 +49,11 @@ describe(`Electric Integration`, () => {
getId: (item: Row) => item.id,
}

const { options, awaitTxId: txIdFn } = electricCollectionOptions(config)
collection = new Collection(options)
awaitTxId = txIdFn
// Get the options with utilities
const options = electricCollectionOptions(config)

// Create collection with Electric configuration using the new utility exposure pattern
collection = createCollection<Row, ElectricCollectionUtils>(options)
})

it(`should handle incoming insert messages and commit on up-to-date`, () => {
Expand Down Expand Up @@ -210,7 +213,7 @@ describe(`Electric Integration`, () => {
])

// The txid should be tracked and awaitTxId should resolve immediately
await expect(awaitTxId(testTxid)).resolves.toBe(true)
await expect(collection.utils.awaitTxId(testTxid)).resolves.toBe(true)
})

it(`should track multiple txids`, async () => {
Expand All @@ -233,8 +236,8 @@ describe(`Electric Integration`, () => {
])

// Both txids should be tracked
await expect(awaitTxId(txid1)).resolves.not.toThrow()
await expect(awaitTxId(txid2)).resolves.not.toThrow()
await expect(collection.utils.awaitTxId(txid1)).resolves.not.toThrow()
await expect(collection.utils.awaitTxId(txid2)).resolves.not.toThrow()
})

it(`should reject with timeout when waiting for unknown txid`, async () => {
Expand All @@ -243,7 +246,7 @@ describe(`Electric Integration`, () => {
const shortTimeout = 100

// Attempt to await a txid that hasn't been seen with a short timeout
const promise = awaitTxId(unknownTxid, shortTimeout)
const promise = collection.utils.awaitTxId(unknownTxid, shortTimeout)

// The promise should reject with a timeout error
await expect(promise).rejects.toThrow(
Expand All @@ -255,7 +258,7 @@ describe(`Electric Integration`, () => {
const laterTxid = `1000`

// Start waiting for a txid that hasn't arrived yet
const promise = awaitTxId(laterTxid, 1000)
const promise = collection.utils.awaitTxId(laterTxid, 1000)

// Send the txid after a short delay
setTimeout(() => {
Expand Down Expand Up @@ -345,7 +348,7 @@ describe(`Electric Integration`, () => {
}

// Start waiting for the txid
const promise = awaitTxId(txid, 1000)
const promise = collection.utils.awaitTxId(txid, 1000)

// Simulate the server sending sync messages after a delay
setTimeout(() => {
Expand Down Expand Up @@ -402,7 +405,7 @@ describe(`Electric Integration`, () => {
onDelete,
}

const { options } = electricCollectionOptions(config)
const options = electricCollectionOptions(config)

// Verify that the handlers were passed to the collection options
expect(options.onInsert).toBeDefined()
Expand Down Expand Up @@ -430,7 +433,7 @@ describe(`Electric Integration`, () => {
onInsert,
}

const { options } = electricCollectionOptions(config)
const options = electricCollectionOptions(config)

// Call the wrapped handler and expect it to throw
await expect(options.onInsert!(mockParams)).rejects.toThrow(
Expand Down Expand Up @@ -514,8 +517,7 @@ describe(`Electric Integration`, () => {
onInsert,
}

const { options } = electricCollectionOptions(config)
const testCollection = new Collection(options)
const testCollection = createCollection(electricCollectionOptions(config))

// Insert data using the transaction
const tx = testCollection.insert({
Expand Down
Loading