Skip to content

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 maxRetriesNumber) 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.

This utility is useful for managing transactional side effects, such as updates to external systems, and ensures proper cleanup in case of failure.

Additionally, this enables hooks like useTransactionEffect(), which allows defining effects with automatic rollback mechanisms.

Type Parameters ​

• T

• K = any

• Args extends any[] = any[]

Parameters ​

• fn

The target function to wrap with transaction handling.

• options?: WithTransactionOptions = {}

Configuration options for the transaction handling.

Returns ​

Function

Parameters ​

• this: K

• ...args: Args

Returns ​

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.');
});