From 6e1b095d04726c0b6ffc15e291476106d3184588 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Mon, 9 Jun 2025 14:29:32 -0600 Subject: [PATCH 01/11] Add types for onX handlers --- .gitignore | 16 +++++++++ packages/db/src/types.ts | 18 ++++++++++ packages/db/tests/collection.test.ts | 52 ++++++++++++++++++++++++++++ 3 files changed, 86 insertions(+) diff --git a/.gitignore b/.gitignore index c48b9be996..3259c89562 100644 --- a/.gitignore +++ b/.gitignore @@ -129,3 +129,19 @@ dist .yarn/install-state.gz .pnp.* .DS_Store + +# Added by Task Master AI +dev-debug.log +# Environment variables +# Editor directories and files +.idea +.vscode +*.suo +*.ntvs* +*.njsproj +*.sln +*.sw? +# OS specific +# Task files +tasks.json +tasks/ diff --git a/packages/db/src/types.ts b/packages/db/src/types.ts index c9a007bbf2..caac9164e5 100644 --- a/packages/db/src/types.ts +++ b/packages/db/src/types.ts @@ -130,6 +130,24 @@ export interface CollectionConfig> { * getId: (item) => item.uuid */ getId: (item: T) => any + /** + * Optional asynchronous handler function called before an insert operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onInsert?: MutationFn + /** + * Optional asynchronous handler function called before an update operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onUpdate?: MutationFn + /** + * Optional asynchronous handler function called before a delete operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to any value + */ + onDelete?: MutationFn } export type ChangesPayload> = Array< diff --git a/packages/db/tests/collection.test.ts b/packages/db/tests/collection.test.ts index 173bbae39b..aa88f90b85 100644 --- a/packages/db/tests/collection.test.ts +++ b/packages/db/tests/collection.test.ts @@ -576,6 +576,58 @@ describe(`Collection`, () => { tx2.mutate(() => collection.insert({ id: 2, value: `new value` })) }).not.toThrow() }) + + it(`should support operation handler functions`, async () => { + // Create mock handler functions + const onInsertMock = vi.fn() + const onUpdateMock = vi.fn() + const onDeleteMock = vi.fn() + + // Create a collection with handler functions + const collection = new Collection<{ id: number; value: string }>({ + id: `handlers-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + begin() + write({ + type: `insert`, + value: { id: 1, value: `initial value` }, + }) + commit() + }, + }, + // Add the new handler functions + onInsert: onInsertMock, + onUpdate: onUpdateMock, + onDelete: onDeleteMock, + }) + + await collection.stateWhenReady() + + // Create a transaction to test the handlers + const mutationFn = async () => {} + const tx = createTransaction({ mutationFn, autoCommit: false }) + + // Test insert handler + tx.mutate(() => collection.insert({ id: 2, value: `new value` })) + + // Test update handler + tx.mutate(() => + collection.update(1, (draft) => { + draft.value = `updated value` + }) + ) + + // Test delete handler + tx.mutate(() => collection.delete(1)) + + // Verify the handler functions were defined correctly + // We're not testing actual invocation since that would require modifying the Collection class + expect(typeof collection.config.onInsert).toBe(`function`) + expect(typeof collection.config.onUpdate).toBe(`function`) + expect(typeof collection.config.onDelete).toBe(`function`) + }) }) describe(`Collection with schema validation`, () => { From 4f38f24def2c321244aa8a06585f58cf693c0737 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Mon, 9 Jun 2025 15:07:19 -0600 Subject: [PATCH 02/11] Implement calling onX handlers --- packages/db/src/collection.ts | 147 +++++++++++++++++++++------ packages/db/tests/collection.test.ts | 126 ++++++++++++++++++++++- 2 files changed, 240 insertions(+), 33 deletions(-) diff --git a/packages/db/src/collection.ts b/packages/db/src/collection.ts index 461b27d0d1..3179a2170f 100644 --- a/packages/db/src/collection.ts +++ b/packages/db/src/collection.ts @@ -1,6 +1,6 @@ import { Derived, Store, batch } from "@tanstack/store" import { withArrayChangeTracking, withChangeTracking } from "./proxy" -import { getActiveTransaction } from "./transactions" +import { Transaction, getActiveTransaction } from "./transactions" import { SortedMap } from "./SortedMap" import type { ChangeMessage, @@ -10,7 +10,7 @@ import type { OptimisticChangeMessage, PendingMutation, StandardSchema, - Transaction, + Transaction as TransactionType, } from "./types" // Store collections in memory using Tanstack store @@ -169,7 +169,7 @@ export class SchemaValidationError extends Error { } export class Collection> { - public transactions: Store> + public transactions: Store> public optimisticOperations: Derived>> public derivedState: Derived> public derivedArray: Derived> @@ -218,7 +218,7 @@ export class Collection> { } this.transactions = new Store( - new SortedMap( + new SortedMap( (a, b) => a.createdAt.getTime() - b.createdAt.getTime() ) ) @@ -604,7 +604,7 @@ export class Collection> { * Inserts one or more items into the collection * @param items - Single item or array of items to insert * @param config - Optional configuration including metadata and custom keys - * @returns A Transaction object representing the insert operation(s) + * @returns A TransactionType object representing the insert operation(s) * @throws {SchemaValidationError} If the data fails schema validation * @example * // Insert a single item @@ -620,9 +620,13 @@ export class Collection> { * insert({ text: "Buy groceries" }, { key: "grocery-task" }) */ insert = (data: T | Array, config?: InsertConfig) => { - const transaction = getActiveTransaction() - if (typeof transaction === `undefined`) { - throw `no transaction found when calling collection.insert` + const ambientTransaction = getActiveTransaction() + + // If no ambient transaction exists, check for an onInsert handler early + if (!ambientTransaction && !this.config.onInsert) { + throw new Error( + `Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.` + ) } const items = Array.isArray(data) ? data : [data] @@ -662,14 +666,37 @@ export class Collection> { mutations.push(mutation) }) - transaction.applyMutations(mutations) + // If an ambient transaction exists, use it + if (ambientTransaction) { + ambientTransaction.applyMutations(mutations) - this.transactions.setState((sortedMap) => { - sortedMap.set(transaction.id, transaction) - return sortedMap - }) + this.transactions.setState((sortedMap) => { + sortedMap.set(ambientTransaction.id, ambientTransaction) + return sortedMap + }) + + return ambientTransaction + } else { + // Create a new transaction with a mutation function that calls the onInsert handler + const directOpTransaction = new Transaction({ + mutationFn: async (params) => { + // Call the onInsert handler with the transaction + return this.config.onInsert!(params) + }, + }) + + // Apply mutations to the new transaction + directOpTransaction.applyMutations(mutations) + directOpTransaction.commit() - return transaction + // Add the transaction to the collection's transactions store + this.transactions.setState((sortedMap) => { + sortedMap.set(directOpTransaction.id, directOpTransaction) + return sortedMap + }) + + return directOpTransaction + } } /** @@ -715,13 +742,13 @@ export class Collection> { id: unknown, configOrCallback: ((draft: TItem) => void) | OperationConfig, maybeCallback?: (draft: TItem) => void - ): Transaction + ): TransactionType update( ids: Array, configOrCallback: ((draft: Array) => void) | OperationConfig, maybeCallback?: (draft: Array) => void - ): Transaction + ): TransactionType update( ids: unknown | Array, @@ -732,9 +759,13 @@ export class Collection> { throw new Error(`The first argument to update is missing`) } - const transaction = getActiveTransaction() - if (typeof transaction === `undefined`) { - throw `no transaction found when calling collection.update` + const ambientTransaction = getActiveTransaction() + + // If no ambient transaction exists, check for an onUpdate handler early + if (!ambientTransaction && !this.config.onUpdate) { + throw new Error( + `Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.` + ) } const isArray = Array.isArray(ids) @@ -828,21 +859,46 @@ export class Collection> { throw new Error(`No changes were made to any of the objects`) } - transaction.applyMutations(mutations) + // If an ambient transaction exists, use it + if (ambientTransaction) { + ambientTransaction.applyMutations(mutations) + + this.transactions.setState((sortedMap) => { + sortedMap.set(ambientTransaction.id, ambientTransaction) + return sortedMap + }) + + return ambientTransaction + } + + // No need to check for onUpdate handler here as we've already checked at the beginning + // Create a new transaction with a mutation function that calls the onUpdate handler + const directOpTransaction = new Transaction({ + mutationFn: async (transaction) => { + // Call the onUpdate handler with the transaction + return this.config.onUpdate!(transaction) + }, + }) + + // Apply mutations to the new transaction + directOpTransaction.applyMutations(mutations) + directOpTransaction.commit() + + // Add the transaction to the collection's transactions store this.transactions.setState((sortedMap) => { - sortedMap.set(transaction.id, transaction) + sortedMap.set(directOpTransaction.id, directOpTransaction) return sortedMap }) - return transaction + return directOpTransaction } /** * Deletes one or more items from the collection * @param ids - Single ID or array of IDs to delete * @param config - Optional configuration including metadata - * @returns A Transaction object representing the delete operation(s) + * @returns A TransactionType object representing the delete operation(s) * @example * // Delete a single item * delete("todo-1") @@ -853,10 +909,17 @@ export class Collection> { * // Delete with metadata * delete("todo-1", { metadata: { reason: "completed" } }) */ - delete = (ids: Array | string, config?: OperationConfig) => { - const transaction = getActiveTransaction() - if (typeof transaction === `undefined`) { - throw `no transaction found when calling collection.delete` + delete = ( + ids: Array | string, + config?: OperationConfig + ): TransactionType => { + const ambientTransaction = getActiveTransaction() + + // If no ambient transaction exists, check for an onDelete handler early + if (!ambientTransaction && !this.config.onDelete) { + throw new Error( + `Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.` + ) } const idsArray = (Array.isArray(ids) ? ids : [ids]).map((id) => @@ -885,14 +948,38 @@ export class Collection> { mutations.push(mutation) } - transaction.applyMutations(mutations) + // If an ambient transaction exists, use it + if (ambientTransaction) { + ambientTransaction.applyMutations(mutations) + + this.transactions.setState((sortedMap) => { + sortedMap.set(ambientTransaction.id, ambientTransaction) + return sortedMap + }) + + return ambientTransaction + } + + // Create a new transaction with a mutation function that calls the onDelete handler + const directOpTransaction = new Transaction({ + autoCommit: true, + mutationFn: async (transaction) => { + // Call the onDelete handler with the transaction + return this.config.onDelete!(transaction) + }, + }) + + // Apply mutations to the new transaction + directOpTransaction.applyMutations(mutations) + directOpTransaction.commit() + // Add the transaction to the collection's transactions store this.transactions.setState((sortedMap) => { - sortedMap.set(transaction.id, transaction) + sortedMap.set(directOpTransaction.id, directOpTransaction) return sortedMap }) - return transaction + return directOpTransaction } /** diff --git a/packages/db/tests/collection.test.ts b/packages/db/tests/collection.test.ts index aa88f90b85..ef830e6573 100644 --- a/packages/db/tests/collection.test.ts +++ b/packages/db/tests/collection.test.ts @@ -44,19 +44,25 @@ describe(`Collection`, () => { // Verify that insert throws an error expect(() => { collection.insert({ value: `new value` }) - }).toThrow(`no transaction found when calling collection.insert`) + }).toThrow( + `Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.` + ) // Verify that update throws an error expect(() => { collection.update(`initial`, (draft) => { draft.value = `updated value` }) - }).toThrow(`no transaction found when calling collection.update`) + }).toThrow( + `Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.` + ) // Verify that delete throws an error expect(() => { collection.delete(`initial`) - }).toThrow(`no transaction found when calling collection.delete`) + }).toThrow( + `Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.` + ) }) it(`should throw an error when trying to update an item's ID`, async () => { @@ -628,6 +634,120 @@ describe(`Collection`, () => { expect(typeof collection.config.onUpdate).toBe(`function`) expect(typeof collection.config.onDelete).toBe(`function`) }) + + it.only(`should execute operations outside of explicit transactions using handlers`, async () => { + // Create handler functions that resolve after a short delay to simulate async operations + const onInsertMock = vi.fn().mockImplementation(async (tx) => { + // Wait a bit to simulate an async operation + await new Promise((resolve) => setTimeout(resolve, 10)) + return { success: true, operation: `insert` } + }) + + const onUpdateMock = vi.fn().mockImplementation(async (tx) => { + await new Promise((resolve) => setTimeout(resolve, 10)) + return { success: true, operation: `update` } + }) + + const onDeleteMock = vi.fn().mockImplementation(async (tx) => { + await new Promise((resolve) => setTimeout(resolve, 10)) + return { success: true, operation: `delete` } + }) + + // Create a collection with handler functions + const collection = new Collection<{ id: number; value: string }>({ + id: `direct-operations-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + begin() + write({ + type: `insert`, + value: { id: 1, value: `initial value` }, + }) + commit() + }, + }, + // Add the handler functions + onInsert: onInsertMock, + onUpdate: onUpdateMock, + onDelete: onDeleteMock, + }) + + await collection.stateWhenReady() + + // Test direct insert operation + const insertTx = collection.insert({ id: 2, value: `inserted directly` }) + expect(insertTx).toBeDefined() + expect(onInsertMock).toHaveBeenCalledTimes(1) + + // Test direct update operation + const updateTx = collection.update(1, (draft) => { + draft.value = `updated directly` + }) + expect(updateTx).toBeDefined() + expect(onUpdateMock).toHaveBeenCalledTimes(1) + + // Test direct delete operation + const deleteTx = collection.delete(1) + expect(deleteTx).toBeDefined() + expect(onDeleteMock).toHaveBeenCalledTimes(1) + + // Wait for all transactions to complete + await Promise.all([ + insertTx.isPersisted.promise, + updateTx.isPersisted.promise, + deleteTx.isPersisted.promise, + ]) + + // Verify the transactions were created with the correct configuration + expect(insertTx.autoCommit).toBe(true) + expect(updateTx.autoCommit).toBe(true) + expect(deleteTx.autoCommit).toBe(true) + }) + + it(`should throw errors when operations are called outside transactions without handlers`, async () => { + // Create a collection without handler functions + const collection = new Collection<{ id: number; value: string }>({ + id: `no-handlers-test`, + getId: (item) => item.id, + sync: { + sync: ({ begin, write, commit }) => { + begin() + write({ + type: `insert`, + value: { id: 1, value: `initial value` }, + }) + commit() + }, + }, + // No handler functions defined + }) + + await collection.stateWhenReady() + + // Test insert without handler + expect(() => { + collection.insert({ id: 2, value: `should fail` }) + }).toThrow( + `Collection.insert called directly (not within an explicit transaction) but no 'onInsert' handler is configured.` + ) + + // Test update without handler + expect(() => { + collection.update(1, (draft) => { + draft.value = `should fail` + }) + }).toThrow( + `Collection.update called directly (not within an explicit transaction) but no 'onUpdate' handler is configured.` + ) + + // Test delete without handler + expect(() => { + collection.delete(1) + }).toThrow( + `Collection.delete called directly (not within an explicit transaction) but no 'onDelete' handler is configured.` + ) + }) }) describe(`Collection with schema validation`, () => { From eb0c93b6a411d73ecec667c1420eb176d6eb0ab8 Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Mon, 9 Jun 2025 15:52:27 -0600 Subject: [PATCH 03/11] wrap onX calls in query collections so refetch is called automatically --- packages/db-collections/src/query.ts | 77 +++++++++++- packages/db-collections/tests/query.test.ts | 129 ++++++++++++++++++++ 2 files changed, 205 insertions(+), 1 deletion(-) diff --git a/packages/db-collections/src/query.ts b/packages/db-collections/src/query.ts index e594e81a39..8dc0821e74 100644 --- a/packages/db-collections/src/query.ts +++ b/packages/db-collections/src/query.ts @@ -5,7 +5,11 @@ import type { QueryKey, QueryObserverOptions, } from "@tanstack/query-core" -import type { CollectionConfig, SyncConfig } from "@tanstack/db" +import type { + CollectionConfig, + MutationFnParams, + SyncConfig, +} from "@tanstack/db" export interface QueryCollectionConfig< TItem extends object, @@ -52,6 +56,28 @@ export interface QueryCollectionConfig< getId: CollectionConfig[`getId`] schema?: CollectionConfig[`schema`] sync?: CollectionConfig[`sync`] + + // Direct persistence handlers + /** + * Optional asynchronous handler function called before an insert operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to void or { refetch?: boolean } to control refetching + */ + onInsert?: CollectionConfig[`onInsert`] + + /** + * Optional asynchronous handler function called before an update operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to void or { refetch?: boolean } to control refetching + */ + onUpdate?: CollectionConfig[`onUpdate`] + + /** + * Optional asynchronous handler function called before a delete operation + * @param params Object containing transaction and mutation information + * @returns Promise resolving to void or { refetch?: boolean } to control refetching + */ + onDelete?: CollectionConfig[`onDelete`] } /** @@ -80,6 +106,9 @@ export function queryCollectionOptions< retryDelay, staleTime, getId, + onInsert, + onUpdate, + onDelete, ...baseCollectionConfig } = config @@ -243,11 +272,57 @@ export function queryCollectionOptions< } } + // Create wrapper handlers for direct persistence operations that handle refetching + const wrappedOnInsert = onInsert + ? async (params: MutationFnParams) => { + const handlerResult = (await onInsert(params)) ?? {} + const shouldRefetch = + (handlerResult as { refetch?: boolean }).refetch !== false + + if (shouldRefetch) { + await refetch() + } + + return handlerResult + } + : undefined + + const wrappedOnUpdate = onUpdate + ? async (params: MutationFnParams) => { + const handlerResult = (await onUpdate(params)) ?? {} + const shouldRefetch = + (handlerResult as { refetch?: boolean }).refetch !== false + + if (shouldRefetch) { + await refetch() + } + + return handlerResult + } + : undefined + + const wrappedOnDelete = onDelete + ? async (params: MutationFnParams) => { + const handlerResult = (await onDelete(params)) ?? {} + const shouldRefetch = + (handlerResult as { refetch?: boolean }).refetch !== false + + if (shouldRefetch) { + await refetch() + } + + return handlerResult + } + : undefined + return { collectionOptions: { ...baseCollectionConfig, getId, sync: { sync: internalSync }, + onInsert: wrappedOnInsert, + onUpdate: wrappedOnUpdate, + onDelete: wrappedOnDelete, }, refetch, } diff --git a/packages/db-collections/tests/query.test.ts b/packages/db-collections/tests/query.test.ts index 12c966ea47..55a90c6601 100644 --- a/packages/db-collections/tests/query.test.ts +++ b/packages/db-collections/tests/query.test.ts @@ -2,6 +2,7 @@ import { afterEach, beforeEach, describe, expect, it, vi } from "vitest" import { QueryClient } from "@tanstack/query-core" import { Collection } from "@tanstack/db" import { queryCollectionOptions } from "../src/query" +import type { MutationFnParams, Transaction } from "@tanstack/db" import type { QueryCollectionConfig } from "../src/query" interface TestItem { @@ -432,4 +433,132 @@ describe(`QueryCollection`, () => { updatedItems[1] ) }) + + describe(`Direct persistence handlers`, () => { + it(`should pass through direct persistence handlers to collection options`, async () => { + const queryKey = [`directPersistenceTest`] + const items = [{ id: `1`, name: `Item 1` }] + const queryFn = vi.fn().mockResolvedValue(items) + + // Create mock handlers + const onInsert = vi.fn().mockResolvedValue(undefined) + const onUpdate = vi.fn().mockResolvedValue(undefined) + const onDelete = vi.fn().mockResolvedValue(undefined) + + const config: QueryCollectionConfig = { + id: `test`, + queryClient, + queryKey, + queryFn, + getId, + onInsert, + onUpdate, + onDelete, + } + + const { collectionOptions } = queryCollectionOptions(config) + + // Verify that the handlers were passed to the collection options + expect(collectionOptions.onInsert).toBeDefined() + expect(collectionOptions.onUpdate).toBeDefined() + expect(collectionOptions.onDelete).toBeDefined() + }) + + it(`should wrap handlers and call the original handler`, async () => { + const queryKey = [`handlerTest`] + const items = [{ id: `1`, name: `Item 1` }] + const queryFn = vi.fn().mockResolvedValue(items) + + // Create a mock transaction for testing + const mockTransaction = { id: `test-transaction` } as Transaction + const mockParams: MutationFnParams = { transaction: mockTransaction } + + // Create handlers + const onInsert = vi.fn().mockResolvedValue(undefined) + const onUpdate = vi.fn().mockResolvedValue(undefined) + const onDelete = vi.fn().mockResolvedValue(undefined) + + const config: QueryCollectionConfig = { + id: `test`, + queryClient, + queryKey, + queryFn, + getId, + onInsert, + onUpdate, + onDelete, + } + + const { collectionOptions } = queryCollectionOptions(config) + + // Call the wrapped handlers + await collectionOptions.onInsert!(mockParams) + await collectionOptions.onUpdate!(mockParams) + await collectionOptions.onDelete!(mockParams) + + // Verify the original handlers were called + expect(onInsert).toHaveBeenCalledWith(mockParams) + expect(onUpdate).toHaveBeenCalledWith(mockParams) + expect(onDelete).toHaveBeenCalledWith(mockParams) + }) + + it(`should call refetch based on handler return value`, async () => { + // Create a mock transaction for testing + const mockTransaction = { id: `test-transaction` } as Transaction + const mockParams: MutationFnParams = { transaction: mockTransaction } + + // Create handlers with different return values + const onInsertDefault = vi.fn().mockResolvedValue(undefined) // Default behavior should refetch + const onInsertFalse = vi.fn().mockResolvedValue({ refetch: false }) // No refetch + + // Create a spy on the refetch function itself + const refetchSpy = vi.fn().mockResolvedValue(undefined) + + // Create configs with the handlers + const configDefault: QueryCollectionConfig = { + id: `test-default`, + queryClient, + queryKey: [`refetchTest`, `default`], + queryFn: vi.fn().mockResolvedValue([{ id: `1`, name: `Item 1` }]), + getId, + onInsert: onInsertDefault, + } + + const configFalse: QueryCollectionConfig = { + id: `test-false`, + queryClient, + queryKey: [`refetchTest`, `false`], + queryFn: vi.fn().mockResolvedValue([{ id: `1`, name: `Item 1` }]), + getId, + onInsert: onInsertFalse, + } + + // Mock the queryClient.refetchQueries method which is called by refetch() + vi.spyOn(queryClient, `refetchQueries`).mockImplementation(refetchSpy) + + // Test case 1: Default behavior (undefined return) should trigger refetch + const { collectionOptions: optionsDefault } = + queryCollectionOptions(configDefault) + await optionsDefault.onInsert!(mockParams) + + // Verify handler was called and refetch was triggered + expect(onInsertDefault).toHaveBeenCalledWith(mockParams) + expect(refetchSpy).toHaveBeenCalledTimes(1) + + // Reset mocks + refetchSpy.mockClear() + + // Test case 2: Explicit { refetch: false } should not trigger refetch + const { collectionOptions: optionsFalse } = + queryCollectionOptions(configFalse) + await optionsFalse.onInsert!(mockParams) + + // Verify handler was called but refetch was NOT triggered + expect(onInsertFalse).toHaveBeenCalledWith(mockParams) + expect(refetchSpy).not.toHaveBeenCalled() + + // Restore original function + vi.restoreAllMocks() + }) + }) }) From 754c53d81dbf798be522fec3cf97fd123ae2f8ee Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Mon, 9 Jun 2025 16:45:38 -0600 Subject: [PATCH 04/11] Implement onX for electric that enforces returning txid & make txid a string --- packages/db-collections/src/electric.ts | 100 ++++++++- .../db-collections/tests/electric.test.ts | 197 ++++++++++++++++-- 2 files changed, 275 insertions(+), 22 deletions(-) diff --git a/packages/db-collections/src/electric.ts b/packages/db-collections/src/electric.ts index 4b95c38a40..9b6f4cb6cc 100644 --- a/packages/db-collections/src/electric.ts +++ b/packages/db-collections/src/electric.ts @@ -4,7 +4,11 @@ import { isControlMessage, } from "@electric-sql/client" import { Store } from "@tanstack/store" -import type { CollectionConfig, SyncConfig } from "@tanstack/db" +import type { + CollectionConfig, + MutationFnParams, + SyncConfig, +} from "@tanstack/db" import type { ControlMessage, Message, @@ -28,6 +32,30 @@ export interface ElectricCollectionConfig> { schema?: CollectionConfig[`schema`] getId: CollectionConfig[`getId`] sync?: CollectionConfig[`sync`] + + /** + * Optional asynchronous handler function called before an insert operation + * Must return an object containing a txid string + * @param params Object containing transaction and mutation information + * @returns Promise resolving to an object with txid + */ + onInsert?: (params: MutationFnParams) => Promise<{ txid: string } | undefined> + + /** + * Optional asynchronous handler function called before an update operation + * Must return an object containing a txid string + * @param params Object containing transaction and mutation information + * @returns Promise resolving to an object with txid + */ + onUpdate?: (params: MutationFnParams) => Promise<{ txid: string } | undefined> + + /** + * Optional asynchronous handler function called before a delete operation + * Must return an object containing a txid string + * @param params Object containing transaction and mutation information + * @returns Promise resolving to an object with txid + */ + onDelete?: (params: MutationFnParams) => Promise<{ txid: string } | undefined> } function isUpToDateMessage = Row>( @@ -57,20 +85,20 @@ export function electricCollectionOptions>( config: ElectricCollectionConfig ): { collectionOptions: CollectionConfig - awaitTxId: (txId: number, timeout?: number) => Promise + awaitTxId: (txId: string, timeout?: number) => Promise } { - const seenTxids = new Store>(new Set([Math.random()])) + const seenTxids = new Store>(new Set([`${Math.random()}`])) const sync = createElectricSync(config.shapeOptions, { seenTxids, }) /** * Wait for a specific transaction ID to be synced - * @param txId The transaction ID to wait for + * @param txId The transaction ID to wait for as a string * @param timeout Optional timeout in milliseconds (defaults to 30000ms) * @returns Promise that resolves when the txId is synced */ - const awaitTxId = async (txId: number, timeout = 30000): Promise => { + const awaitTxId = async (txId: string, timeout = 30000): Promise => { const hasTxid = seenTxids.state.has(txId) if (hasTxid) return true @@ -90,13 +118,65 @@ export function electricCollectionOptions>( }) } + // Create wrapper handlers for direct persistence operations that handle txid awaiting + const wrappedOnInsert = config.onInsert + ? async (params: MutationFnParams) => { + const handlerResult = (await config.onInsert!(params)) ?? {} + const txid = (handlerResult as { txid?: string }).txid + + if (!txid) { + throw new Error( + `Electric collection onInsert handler must return a txid` + ) + } + + await awaitTxId(txid) + return handlerResult + } + : undefined + + const wrappedOnUpdate = config.onUpdate + ? async (params: MutationFnParams) => { + const handlerResult = await config.onUpdate!(params) + const txid = (handlerResult as { txid?: string }).txid + + if (!txid) { + throw new Error( + `Electric collection onUpdate handler must return a txid` + ) + } + + await awaitTxId(txid) + return handlerResult + } + : undefined + + const wrappedOnDelete = config.onDelete + ? async (params: MutationFnParams) => { + const handlerResult = await config.onDelete!(params) + const txid = (handlerResult as { txid?: string }).txid + + if (!txid) { + throw new Error( + `Electric collection onDelete handler must return a txid` + ) + } + + await awaitTxId(txid) + return handlerResult + } + : undefined + // Extract standard Collection config properties - const { shapeOptions, ...restConfig } = config + const { shapeOptions, onInsert, onUpdate, onDelete, ...restConfig } = config return { collectionOptions: { ...restConfig, sync, + onInsert: wrappedOnInsert, + onUpdate: wrappedOnUpdate, + onDelete: wrappedOnDelete, }, awaitTxId, } @@ -108,7 +188,7 @@ export function electricCollectionOptions>( function createElectricSync>( shapeOptions: ShapeStreamOptions, options: { - seenTxids: Store> + seenTxids: Store> } ): SyncConfig { const { seenTxids } = options @@ -136,7 +216,7 @@ function createElectricSync>( const { begin, write, commit } = params const stream = new ShapeStream(shapeOptions) let transactionStarted = false - let newTxids = new Set() + let newTxids = new Set() stream.subscribe((messages: Array>) => { let hasUpToDate = false @@ -144,7 +224,7 @@ function createElectricSync>( for (const message of messages) { // Check for txids in the message and add them to our store if (hasTxids(message) && message.headers.txids) { - message.headers.txids.forEach((txid) => newTxids.add(txid)) + message.headers.txids.forEach((txid) => newTxids.add(String(txid))) } // Check if the message contains schema information @@ -183,7 +263,7 @@ function createElectricSync>( commit() seenTxids.setState((currentTxids) => { const clonedSeen = new Set(currentTxids) - newTxids.forEach((txid) => clonedSeen.add(txid)) + newTxids.forEach((txid) => clonedSeen.add(String(txid))) newTxids = new Set() return clonedSeen diff --git a/packages/db-collections/tests/electric.test.ts b/packages/db-collections/tests/electric.test.ts index c28a02d19c..f22f9e51f2 100644 --- a/packages/db-collections/tests/electric.test.ts +++ b/packages/db-collections/tests/electric.test.ts @@ -1,7 +1,11 @@ import { beforeEach, describe, expect, it, vi } from "vitest" import { Collection, createTransaction } from "@tanstack/db" import { electricCollectionOptions } from "../src/electric" -import type { PendingMutation, Transaction } from "@tanstack/db" +import type { + MutationFnParams, + PendingMutation, + Transaction, +} from "@tanstack/db" import type { Message, Row } from "@electric-sql/client" // Mock the ShapeStream module @@ -20,7 +24,7 @@ vi.mock(`@electric-sql/client`, async () => { describe(`Electric Integration`, () => { let collection: Collection - let awaitTxId: (txId: number, timeout?: number) => Promise + let awaitTxId: (txId: string, timeout?: number) => Promise let subscriber: (messages: Array>) => void beforeEach(() => { @@ -189,7 +193,7 @@ describe(`Electric Integration`, () => { // Tests for txid tracking functionality describe(`txid tracking`, () => { it(`should track txids from incoming messages`, async () => { - const testTxid = 123 + const testTxid = `123` // Send a message with a txid subscriber([ @@ -210,9 +214,9 @@ describe(`Electric Integration`, () => { await expect(awaitTxId(testTxid)).resolves.toBe(true) }) - it(`should handle multiple txids in a single message`, async () => { - const txid1 = 1 - const txid2 = 2 + it(`should track multiple txids`, async () => { + const txid1 = `100` + const txid2 = `200` // Send a message with multiple txids subscriber([ @@ -236,7 +240,7 @@ describe(`Electric Integration`, () => { it(`should reject with timeout when waiting for unknown txid`, async () => { // Set a short timeout for the test - const unknownTxid = 0 + const unknownTxid = `0` const shortTimeout = 100 // Attempt to await a txid that hasn't been seen with a short timeout @@ -249,7 +253,7 @@ describe(`Electric Integration`, () => { }) it(`should resolve when a txid arrives after awaitTxId is called`, async () => { - const laterTxid = 1000 + const laterTxid = `1000` // Start waiting for a txid that hasn't arrived yet const promise = awaitTxId(laterTxid, 1000) @@ -286,10 +290,10 @@ describe(`Electric Integration`, () => { it(`should simulate the complete flow`, async () => { // Create a fake backend store to simulate server-side storage const fakeBackend = { - data: new Map(), + data: new Map(), // Simulates persisting data to a backend and returning a txid - persist: (mutations: Array): Promise => { - const txid = Date.now() + persist: (mutations: Array): Promise => { + const txid = String(Date.now()) // Store the changes with the txid mutations.forEach((mutation) => { @@ -302,7 +306,7 @@ describe(`Electric Integration`, () => { return Promise.resolve(txid) }, // Simulates the server sending sync messages with txids - simulateSyncMessage: (txid: number) => { + simulateSyncMessage: (txid: string) => { // Create messages for each item in the store that has this txid const messages: Array> = [] @@ -376,4 +380,173 @@ describe(`Electric Integration`, () => { expect(collection.state.has(`KEY::${collection.id}/1`)).toBe(true) }) }) + + // Tests for direct persistence handlers + describe(`Direct persistence handlers`, () => { + it(`should pass through direct persistence handlers to collection options`, () => { + // Create mock handlers + const onInsert = vi.fn().mockResolvedValue({ txid: `123` }) + const onUpdate = vi.fn().mockResolvedValue({ txid: `456` }) + const onDelete = vi.fn().mockResolvedValue({ txid: `789` }) + + const config = { + id: `test-handlers`, + shapeOptions: { + url: `http://test-url`, + params: { + table: `test_table`, + }, + }, + getId: (item: Row) => item.id, + onInsert, + onUpdate, + onDelete, + } + + const { collectionOptions } = electricCollectionOptions(config) + + // Verify that the handlers were passed to the collection options + expect(collectionOptions.onInsert).toBeDefined() + expect(collectionOptions.onUpdate).toBeDefined() + expect(collectionOptions.onDelete).toBeDefined() + }) + + it(`should throw an error if handler doesn't return a txid`, async () => { + // Create a mock transaction for testing + const mockTransaction = { id: `test-transaction` } as Transaction + const mockParams: MutationFnParams = { transaction: mockTransaction } + + // Create a handler that doesn't return a txid + const onInsert = vi.fn().mockResolvedValue({}) + + const config = { + id: `test-handlers`, + shapeOptions: { + url: `http://test-url`, + params: { + table: `test_table`, + }, + }, + getId: (item: Row) => item.id, + onInsert, + } + + const { collectionOptions } = electricCollectionOptions(config) + + // Call the wrapped handler and expect it to throw + await expect(collectionOptions.onInsert!(mockParams)).rejects.toThrow( + `Electric collection onInsert handler must return a txid` + ) + }) + + // We no longer need to test for invalid txid format since we're using strings directly + + it(`should simulate complete flow with direct persistence handlers`, async () => { + // Create a fake backend store to simulate server-side storage + const fakeBackend = { + data: new Map(), + // Simulates persisting data to a backend and returning a txid + persist: (mutations: Array): Promise => { + const txid = String(Date.now()) + + // Store the changes with the txid + mutations.forEach((mutation) => { + const key = mutation.key + fakeBackend.data.set(key, { txid, value: mutation.changes }) + }) + + return Promise.resolve(txid) + }, + // Simulates the server sending sync messages with txids + simulateSyncMessage: (txid: string) => { + // Create messages for each item in the store that has this txid + const messages: Array> = [] + + fakeBackend.data.forEach((value, key) => { + if (value.txid === txid) { + messages.push({ + key, + value: value.value as Row, + headers: { + operation: `insert`, + txids: [Number(txid)], // Convert to number as the API expects numbers but our code converts to strings + }, + }) + } + }) + + // Add up-to-date message + messages.push({ + headers: { control: `up-to-date` }, + }) + + // Send the messages to the subscriber + subscriber(messages) + }, + } + + // Create a mutation function for the transaction + const mutationFn = vi.fn(async (params: MutationFnParams) => { + const txid = await fakeBackend.persist(params.transaction.mutations) + + // Simulate server sending sync message after a delay + setTimeout(() => { + fakeBackend.simulateSyncMessage(txid) + }, 50) + + return txid + }) + + // Create direct persistence handler that returns the txid + const onInsert = vi.fn(async (params: MutationFnParams) => { + return { txid: await mutationFn(params) } + }) + + // Create a test collection with our direct persistence handler + const config = { + id: `test-direct-persistence`, + shapeOptions: { + url: `http://test-url`, + params: { + table: `test_table`, + }, + }, + getId: (item: Row) => item.id, + onInsert, + } + + const { collectionOptions } = electricCollectionOptions(config) + const testCollection = new Collection(collectionOptions) + + // Insert data using the transaction + const tx = testCollection.insert({ + id: 1, + name: `Direct Persistence User`, + }) + + // If awaitTxId wasn't called automatically, this wouldn't be true. + expect(testCollection.syncedData.state.size).toEqual(0) + expect( + testCollection.optimisticOperations.state.filter((o) => o.isActive) + .length + ).toEqual(1) + + // Verify that our onInsert handler was called + expect(onInsert).toHaveBeenCalled() + + await tx.isPersisted.promise + + // Verify that the data was added to the collection via the sync process + expect(testCollection.state.has(`KEY::${testCollection.id}/1`)).toBe(true) + expect(testCollection.state.get(`KEY::${testCollection.id}/1`)).toEqual({ + id: 1, + name: `Direct Persistence User`, + }) + expect(testCollection.syncedData.state.size).toEqual(1) + expect( + testCollection.optimisticOperations.state.filter((o) => o.isActive) + .length + ).toEqual(0) + }) + }) }) From 4f971a24b8654f79302a2b559f4e7bf94b27cebd Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Mon, 9 Jun 2025 16:53:06 -0600 Subject: [PATCH 05/11] remove .only --- packages/db/tests/collection.test.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/packages/db/tests/collection.test.ts b/packages/db/tests/collection.test.ts index ef830e6573..71abaeff0a 100644 --- a/packages/db/tests/collection.test.ts +++ b/packages/db/tests/collection.test.ts @@ -635,7 +635,7 @@ describe(`Collection`, () => { expect(typeof collection.config.onDelete).toBe(`function`) }) - it.only(`should execute operations outside of explicit transactions using handlers`, async () => { + it(`should execute operations outside of explicit transactions using handlers`, async () => { // Create handler functions that resolve after a short delay to simulate async operations const onInsertMock = vi.fn().mockImplementation(async (tx) => { // Wait a bit to simulate an async operation From 24b5830ae256aa1e724dd3c92649ae0894667d2b Mon Sep 17 00:00:00 2001 From: Kyle Mathews Date: Tue, 10 Jun 2025 07:15:11 -0600 Subject: [PATCH 06/11] update example --- examples/react/todo/src/App.tsx | 396 ++++++++++++++++---------------- 1 file changed, 196 insertions(+), 200 deletions(-) diff --git a/examples/react/todo/src/App.tsx b/examples/react/todo/src/App.tsx index 57ddb58aa1..e550adee04 100644 --- a/examples/react/todo/src/App.tsx +++ b/examples/react/todo/src/App.tsx @@ -1,10 +1,5 @@ import React, { useState } from "react" -import { - collectionsStore, - createCollection, - useLiveQuery, - useOptimisticMutation, -} from "@tanstack/react-db" +import { createCollection, useLiveQuery } from "@tanstack/react-db" import { electricCollectionOptions, queryCollectionOptions, @@ -140,45 +135,102 @@ const createTodoCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - const { collectionOptions, awaitTxId } = electricCollectionOptions({ - id: `todos`, - shapeOptions: { - url: `http://localhost:3003/v1/shape`, - params: { - table: `todos`, + newCollection = createCollection( + electricCollectionOptions({ + id: `todos`, + shapeOptions: { + url: `http://localhost:3003/v1/shape`, + params: { + table: `todos`, + }, + parser: { + // Parse timestamp columns into JavaScript Date objects + timestamptz: (date: string) => new Date(date), + }, }, - parser: { - // Parse timestamp columns into JavaScript Date objects - timestamptz: (date: string) => new Date(date), + getId: (item) => item.id, + schema: updateTodoSchema, + onInsert: async ({ transaction }) => { + const modified = transaction.mutations[0]!.modified + const response = await api.todos.create(modified) + return { txid: String(response.txid) } }, - }, - getId: (item) => item.id, - schema: updateTodoSchema, - }) - newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId) + onUpdate: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.todos.update(original.id, changes) + return { txid: String(response.txid) } + }) + ) + + return { txid: String(txids[0]) } + }, + onDelete: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.todos.delete(original.id) + return { txid: String(response.txid) } + }) + ) + + return { txid: String(txids[0]) } + }, + }).collectionOptions + ) } else { // Query collection using our API helper - - const { collectionOptions, refetch } = queryCollectionOptions({ - id: `todos`, - queryKey: [`todos`], - refetchInterval: 3000, - queryFn: async () => { - const todos = await api.todos.getAll() - // Turn date strings into Dates if needed - return todos.map((todo) => ({ - ...todo, - created_at: todo.created_at ? new Date(todo.created_at) : undefined, - updated_at: todo.updated_at ? new Date(todo.updated_at) : undefined, - })) - }, - getId: (item: UpdateTodo) => String(item.id), - schema: updateTodoSchema, - queryClient, - }) - newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${newCollection.id}`, refetch) + newCollection = createCollection( + queryCollectionOptions({ + id: `todos`, + queryKey: [`todos`], + refetchInterval: 3000, + queryFn: async () => { + const todos = await api.todos.getAll() + // Turn date strings into Dates if needed + return todos.map((todo) => ({ + ...todo, + created_at: todo.created_at + ? new Date(todo.created_at) + : undefined, + updated_at: todo.updated_at + ? new Date(todo.updated_at) + : undefined, + })) + }, + getId: (item: UpdateTodo) => String(item.id), + schema: updateTodoSchema, + queryClient, + onInsert: async ({ transaction }) => { + const modified = transaction.mutations[0]!.modified + const response = await api.todos.create(modified) + return { txid: String(response.txid) } + }, + onUpdate: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.todos.update(original.id, changes) + return { txid: String(response.txid) } + }) + ) + + return { txid: txids[0] } + }, + onDelete: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.todos.delete(original.id) + return { txid: String(response.txid) } + }) + ) + + return { txid: String(txids[0]) } + }, + }).collectionOptions + ) } collectionsCache.set(`todo`, newCollection) return newCollection @@ -192,80 +244,94 @@ const createConfigCollection = (type: CollectionType) => { } else { let newCollection: Collection if (type === CollectionType.Electric) { - const { collectionOptions, awaitTxId } = electricCollectionOptions({ - id: `config`, - shapeOptions: { - url: `http://localhost:3003/v1/shape`, - params: { - table: `config`, - }, - parser: { - // Parse timestamp columns into JavaScript Date objects - timestamptz: (date: string) => { - return new Date(date) + newCollection = createCollection( + electricCollectionOptions({ + id: `config`, + shapeOptions: { + url: `http://localhost:3003/v1/shape`, + params: { + table: `config`, + }, + parser: { + // Parse timestamp columns into JavaScript Date objects + timestamptz: (date: string) => { + return new Date(date) + }, }, }, - }, - getId: (item: UpdateConfig) => item.id, - schema: updateConfigSchema, - }) - newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${newCollection.id}`, awaitTxId) + getId: (item: UpdateConfig) => item.id, + schema: updateConfigSchema, + onInsert: async ({ transaction }) => { + const modified = transaction.mutations[0]!.modified + const response = await api.config.create(modified) + return { txid: String(response.txid) } + }, + onUpdate: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.config.update( + original.id as number, + changes + ) + return { txid: String(response.txid) } + }) + ) + + return { txid: String(txids[0]) } + }, + }).collectionOptions + ) } else { // Query collection using our API helper - const { collectionOptions, refetch } = queryCollectionOptions({ - id: `config`, - queryKey: [`config`], - refetchInterval: 3000, - queryFn: async () => { - const configs = await api.config.getAll() - // Turn date strings into Dates if needed - return configs.map((config) => ({ - ...config, - created_at: config.created_at - ? new Date(config.created_at) - : undefined, - updated_at: config.updated_at - ? new Date(config.updated_at) - : undefined, - })) - }, - getId: (item: UpdateConfig) => item.id, - schema: updateConfigSchema, - queryClient, - }) - newCollection = createCollection(collectionOptions) - utilityFunctionsCache.set(`${newCollection.id}`, refetch) + newCollection = createCollection( + queryCollectionOptions({ + id: `config`, + queryKey: [`config`], + refetchInterval: 3000, + queryFn: async () => { + const configs = await api.config.getAll() + // Turn date strings into Dates if needed + return configs.map((config) => ({ + ...config, + created_at: config.created_at + ? new Date(config.created_at) + : undefined, + updated_at: config.updated_at + ? new Date(config.updated_at) + : undefined, + })) + }, + getId: (item: UpdateConfig) => item.id, + schema: updateConfigSchema, + queryClient, + onInsert: async ({ transaction }) => { + const modified = transaction.mutations[0]!.modified + const response = await api.config.create(modified) + return { txid: String(response.txid) } + }, + onUpdate: async ({ transaction }) => { + const txids = await Promise.all( + transaction.mutations.map(async (mutation) => { + const { original, changes } = mutation + const response = await api.config.update( + original.id as number, + changes + ) + return { txid: String(response.txid) } + }) + ) + + return { txid: String(txids[0]) } + }, + }).collectionOptions + ) } collectionsCache.set(`config`, newCollection) return newCollection } } -// A bit of indirection to handle awaiting each collection type syncing in new changes. -async function collectionSync( - type: CollectionType, - mutation: PendingMutation, - txid: number -) { - // Get the collection ID from the mutation - const collectionId = mutation.collection.id - - if (type === CollectionType.Query) { - // Get the refetch function from the cache - const refetch = utilityFunctionsCache.get(`${collectionId}`) - if (refetch) { - await refetch() - } - } else { - // Get the awaitTxId function from the cache - const awaitTxId = utilityFunctionsCache.get(`${collectionId}`) - if (awaitTxId) { - await awaitTxId(txid) - } - } -} - export default function App() { // Read collection type from URL param directly const getInitialCollectionType = (): CollectionType => { @@ -296,62 +362,6 @@ export default function App() { .select(`@id`, `@key`, `@value`) ) - // Define mutations - const addTodo = useOptimisticMutation({ - mutationFn: async ({ transaction }) => { - const mutation = transaction.mutations[0] as PendingMutation - - const { modified } = mutation - const response = await api.todos.create(modified) - await collectionSync(collectionType, mutation, response.txid) - }, - }) - - const updateTodo = useOptimisticMutation({ - mutationFn: async ({ transaction }) => { - const txids = await Promise.all( - transaction.mutations.map(async (mutation) => { - const { original, changes } = mutation - const response = await api.todos.update(original.id, changes) - return response.txid - }) - ) - await Promise.all( - txids.map(async (txid, i) => { - const mutation = transaction.mutations[i]! - return await collectionSync(collectionType, mutation, txid) - }) - ) - }, - }) - - const deleteTodo = useOptimisticMutation({ - mutationFn: async ({ transaction }) => { - const mutation = transaction.mutations[0] as PendingMutation - const { original } = mutation - const response = await api.todos.delete(original.id) - await collectionSync(collectionType, mutation, response.txid) - }, - }) - - const createConfig = useOptimisticMutation({ - mutationFn: async ({ transaction }) => { - const mutation = transaction.mutations[0] as PendingMutation - const { modified } = mutation - const response = await api.config.create(modified) - await collectionSync(collectionType, mutation, response.txid) - }, - }) - - const updateConfig = useOptimisticMutation({ - mutationFn: async ({ transaction }) => { - const mutation = transaction.mutations[0] as PendingMutation - const { original, changes } = mutation - const response = await api.config.update(original.id as number, changes) - await collectionSync(collectionType, mutation, response.txid) - }, - }) - // Handle collection type change directly const handleCollectionTypeChange = (type: CollectionType) => { if (type !== collectionType) { @@ -376,23 +386,19 @@ export default function App() { const setConfigValue = (key: string, value: string): void => { for (const config of configData) { if (config.key === key) { - updateConfig.mutate(() => - configCollection.update(config.id, (draft) => { - draft.value = value - }) - ) + configCollection.update(config.id, (draft) => { + draft.value = value + }) return } } // If the config doesn't exist yet, create it - createConfig.mutate(() => - configCollection.insert({ - key, - value, - }) - ) + configCollection.insert({ + key, + value, + }) } const backgroundColor = getConfigValue(`backgroundColor`) @@ -452,22 +458,18 @@ export default function App() { e.preventDefault() if (!newTodo.trim()) return - addTodo.mutate(() => - todoCollection.insert({ - text: newTodo, - completed: false, - id: Math.round(Math.random() * 1000000), - }) - ) + todoCollection.insert({ + text: newTodo, + completed: false, + id: Math.round(Math.random() * 1000000), + }) setNewTodo(``) } const toggleTodo = (todo: UpdateTodo) => { - updateTodo.mutate(() => - todoCollection.update(todo.id, (draft) => { - draft.completed = !draft.completed - }) - ) + todoCollection.update(todo.id, (draft) => { + draft.completed = !draft.completed + }) } const activeTodos = todos.filter((todo) => !todo.completed) @@ -562,15 +564,13 @@ export default function App() { : activeTodos const togglingIds = new Set() todosToToggle.forEach((t) => togglingIds.add(t.id)) - updateTodo.mutate(() => - todoCollection.update( - todosToToggle.map((todo) => todo.id), - (drafts) => { - drafts.forEach( - (draft) => (draft.completed = !allCompleted) - ) - } - ) + todoCollection.update( + todosToToggle.map((todo) => todo.id), + (drafts) => { + drafts.forEach( + (draft) => (draft.completed = !allCompleted) + ) + } ) }} > @@ -613,9 +613,7 @@ export default function App() {