Unit of Work pattern for managing transactions.

Ensures that a group of operations either all succeed or all fail together.

await unitOfWork.transaction(async () => {
await userRepository.save(user);
await orderRepository.save(order);
await eventBus.publish(events);
// All operations committed together
});
interface UnitOfWork {
    transaction<T>(fn: () => Promise<T>): Promise<T>;
    begin(): Promise<void>;
    commit(): Promise<void>;
    rollback(): Promise<void>;
}

Methods

  • Executes a function within a transaction.

    If the function completes successfully, the transaction is committed. If an error is thrown, the transaction is rolled back.

    Type Parameters

    • T

      The return type of the transaction function

    Parameters

    • fn: () => Promise<T>

      The function to execute within the transaction

    Returns Promise<T>

    The result of the transaction function

    The error thrown by the transaction function

    const result = await unitOfWork.transaction(async () => {
    const user = await userRepository.findById('user-123');
    user.updateEmail('newemail@example.com');
    await userRepository.save(user);
    return user;
    });
  • Starts a new transaction.

    Returns Promise<void>

    await unitOfWork.begin();
    try {
    await userRepository.save(user);
    await orderRepository.save(order);
    await unitOfWork.commit();
    } catch (error) {
    await unitOfWork.rollback();
    throw error;
    }