UNPKG

@tanstack/db

Version:

A reactive client store for building super fast apps on sync

73 lines (72 loc) • 2.4 kB
import { createTransaction } from "./transactions.js"; import { QueueDisposedError, QueueCapacityExceededError, DebounceCallDroppedError, ThrottleCallDroppedError } from "./errors.js"; function createPacedMutations(config) { const { onMutate, mutationFn, strategy, ...transactionConfig } = config; let activeTransaction = null; const commitCallback = () => { if (!activeTransaction) { throw new Error( `Strategy callback called but no active transaction exists. This indicates a bug in the strategy implementation.` ); } if (activeTransaction.state !== `pending`) { throw new Error( `Strategy callback called but active transaction is in state "${activeTransaction.state}". Expected "pending".` ); } const txToCommit = activeTransaction; activeTransaction = null; txToCommit.commit().catch(() => { }); return txToCommit; }; function mutate(variables) { if (!activeTransaction || activeTransaction.state !== `pending`) { activeTransaction = createTransaction({ ...transactionConfig, mutationFn, autoCommit: false }); } activeTransaction.mutate(() => { onMutate(variables); }); const txToReturn = activeTransaction; if (strategy._type === `queue`) { activeTransaction = null; let admitted; try { admitted = strategy.execute(() => { txToReturn.commit().catch(() => { }); return txToReturn; }); } catch (error) { if (!(error instanceof QueueDisposedError)) throw error; txToReturn.rollback({ error, isSecondaryRollback: true }); return txToReturn; } if (admitted === false) { txToReturn.rollback({ error: new QueueCapacityExceededError(), isSecondaryRollback: true }); } } else { const executed = strategy.execute(commitCallback); if ((strategy._type === `debounce` || strategy._type === `throttle`) && executed === false) { txToReturn.rollback({ error: strategy._type === `debounce` ? new DebounceCallDroppedError() : new ThrottleCallDroppedError(), isSecondaryRollback: true }); activeTransaction = null; } } return txToReturn; } return mutate; } export { createPacedMutations }; //# sourceMappingURL=paced-mutations.js.map