Documentation / @andrew_l/mongo-transaction / withTransaction
Function: withTransaction()
withTransaction<
T,K,Args>(fn,options?): (this, ...args) =>Promise<Awaited<T>>
Wraps a function with transaction context, enabling retry logic and transactional effects.
The wrapped function may be executed multiple times (up to maxAttempts) to ensure all side effects complete successfully. If the retries are exhausted without success, registered cleanup functions will be executed to undo any applied effects.
Enables useTransactionEffect(), onCommitted() and onRollback() inside fn.
Type Parameters
T
T
K
K = any
Args
Args extends any[] = any[]
Parameters
fn
(this, ...args) => T
The target function to wrap with transaction handling.
options?
Configuration options for the transaction handling.
Returns
(this, ...args) => Promise<Awaited<T>>
Example
ts
const confirmOrder = withTransaction(async (orderId) => {
// Register Alert
await useTransactionEffect(async () => {
const alertId = await alertService.create({
title: 'New Order: ' + orderId,
});
return () => alertService.removeById(alertId); // Cleanup in case of failure
});
// Update Statistics
await useTransactionEffect(async () => {
await statService.increment('orders_amount', 1);
return () => statService.decrement('orders_amount', 1); // Cleanup in case of failure
});
// Simulate failure to trigger rollback
throw new Error('Cancel transaction.');
});