All files / src/transaction transaction-starter.ts

100% Statements 6/6
100% Branches 4/4
100% Functions 4/4
100% Lines 6/6

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54                              848x 848x                   104x                           345x         449x 449x              
import type { ConnectionManager } from '../connection/connection-manager.ts';
import type { RetryRunner } from '../connection/retry.ts';
import { Transaction, type TransactionOptions } from './transaction.ts';
import { transactionScope } from './transaction-runner.ts';
 
/** Creates transactions on a connection manager, nesting them in the CLS transaction when enabled. */
export class TransactionStarter {
  readonly #connections: ConnectionManager;
  readonly #retries: RetryRunner;
 
  /**
   * @param connections - Connection manager of the owning `Sequelize` instance.
   * @param retries - Retry settings of the owning `Sequelize` instance, applied to starting a transaction.
   */
  constructor(connections: ConnectionManager, retries: RetryRunner) {
    this.#connections = connections;
    this.#retries = retries;
  }
 
  /**
   * Starts an unmanaged transaction.
   *
   * @param options - Transaction options.
   * @returns Started transaction.
   */
  begin(options: TransactionOptions): Promise<Transaction> {
    return this.#create(options).begin();
  }
 
  /**
   * Runs `run` in a managed transaction: committed on success, rolled back on error.
   *
   * @param options - Transaction options.
   * @param run - Callback receiving the transaction.
   * @returns Result of `run`.
   */
  managed<T>(
    options: TransactionOptions,
    run: (transaction: Transaction) => Promise<T>,
  ): Promise<T> {
    return transactionScope.run(this.#create(options), run);
  }
 
  #create(options: TransactionOptions): Transaction {
    const parent =
      options.transaction === undefined ? transactionScope.implicitParent() : options.transaction;
    return new Transaction(
      this.#connections,
      { ...options, ...(parent === undefined ? {} : { transaction: parent }) },
      this.#retries,
    );
  }
}