npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@bro-ankit/nestjs-typeorm-transactional-context

v1.0.1

Published

> Transaction management for NestJS with TypeORM supporting propagation and isolation.

Readme

NestJS TypeORM Transactional Context

Transaction management for NestJS with TypeORM supporting propagation and isolation.

npm version License: MIT

Why This Package?

Managing transactions in NestJS can be cumbersome. This library provides:

  • Zero boilerplate - Just add @Transactional() decorator
  • Framework integration - Built specifically for NestJS dependency injection
  • Type safety - Full TypeScript support with proper types
  • Tested - Battle-tested with comprehensive test coverage
  • Lightweight - Minimal dependencies, leverages existing TypeORM

Table of Contents


Features

  • Declarative Transactions - Simple @Transactional() decorator
  • Transaction Propagation - Control nested transaction behavior
  • Transaction-Aware Repositories - Repositories that respect transaction context
  • Isolation Levels - Support for all TypeORM isolation levels
  • Async Context - Works with NestJS's async context
  • TypeScript - Full type safety
  • Testing - Easy to test with dependency injection

Installation

npm install @bro-ankit/nestjs-transactional-context
# or
yarn add @bro-ankit/nestjs-transactional-context
# or
pnpm add @bro-ankit/nestjs-transactional-context

Requirements

  • NestJS 10.x or higher
  • TypeORM 0.3.x or higher
  • Node.js 18.x or higher

Quick Start

1. Import Modules

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { TransactionalModule } from "@bro-ankit/nestjs-transactional-context";

@Module({
  imports: [
    TypeOrmModule.forRoot({
      type: "postgres",
      // ... your database config
    }),
    TransactionalModule, // Required
  ],
})
export class AppModule {}

2. Use the @Transactional() Decorator

import { Injectable } from "@nestjs/common";
import { Repository } from "typeorm";
import { Transactional } from "@bro-ankit/nestjs-transactional-context";
import { User } from "./user.entity";
import { InjectRepository } from "@nestjs/typeorm";

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private readonly userRepository: Repository<User>,
  ) {}

  @Transactional()
  async createUser(name: string, email: string): Promise<User> {
    const user = this.userRepository.create({ name, email });
    await this.userRepository.save(user);

    if (!email.includes("@")) {
      throw new Error("Invalid email"); // rolls back the created user
    }

    return user;
  }
}

3. Create Transaction-Aware Repositories

import { Injectable } from "@nestjs/common";
import { Repository } from "typeorm";
import {
  TransactionalAwareRepository,
  DbTransactionContext,
} from "@bro-ankit/nestjs-transactional-context";
import { User } from "./user.entity";

@Injectable()
@TransactionalAwareRepository(User)
export class UserRepository extends Repository<User> {
  constructor(private readonly ctx: DbTransactionContext) {
    super(User, ctx.getEntityManager());
  }

  async findByEmail(email: string): Promise<User | null> {
    return this.findOne({ where: { email } });
  }

  async createUser(name: string, email: string): Promise<User> {
    const user = this.create({ name, email });
    return this.save(user);
  }
}

Register in your module:

import { Module } from "@nestjs/common";
import { TypeOrmModule } from "@nestjs/typeorm";
import { User } from "./user.entity";
import { UserRepository } from "./user.repository";
import { UserService } from "./user.service";

@Module({
  imports: [TypeOrmModule.forFeature([User])],
  providers: [UserRepository, UserService],
  exports: [UserService],
})
export class UserModule {}

Usage Examples

Basic Transaction

@Injectable()
export class OrderService {
  constructor(private readonly orderRepository: OrderRepository) {}

  @Transactional()
  async createOrder(userId: string, items: OrderItem[]): Promise<Order> {
    const order = this.orderRepository.create({ userId, items });
    await this.orderRepository.save(order);
    return order; // Automatically commits
  }
}

Nested Transactions with Propagation

@Injectable()
export class PaymentService {
  constructor(
    private readonly orderRepository: Repository<Order>,
    private readonly paymentRepository: Repository<Payment>,
    private readonly dbTransactionService: DbTransactionService,
  ) {}

  @Transactional()
  async processPayment(orderId: string): Promise<Payment> {
    const order = await this.orderRepository.findOne({
      where: { id: orderId },
    });
    const payment = await this.createPaymentRecord(order);

    // Independent transaction for logging
    await this.dbTransactionService.executeInTransaction(
      { propagation: false },
      async () => {
        await this.logPaymentAttempt(orderId);
      },
    );

    return payment;
  }

  @Transactional()
  private async createPaymentRecord(order: Order): Promise<Payment> {
    return this.paymentRepository.save({ orderId: order.id } as Payment);
  }

  private async logPaymentAttempt(orderId: string): Promise<void> {
    // logging logic here
  }
}

Manual Transaction Control

@Injectable()
export class ReportService {
  constructor(
    private readonly dbTransactionService: DbTransactionService,
    private readonly orderRepository: OrderRepository,
    private readonly reportRepository: ReportRepository,
  ) {}

  async generateReport(): Promise<Report> {
    return this.dbTransactionService.executeInTransaction(async () => {
      const data = await this.orderRepository.find();
      const processed = await this.processData(data);
      return this.reportRepository.save(processed);
    });
  }
}

Transaction Rollback

@Injectable()
export class AccountService {
  constructor(private readonly accountRepository: AccountRepository) {}

  @Transactional()
  async transfer(fromId: string, toId: string, amount: number): Promise<void> {
    const fromAccount = await this.accountRepository.findOne({
      where: { id: fromId },
    });
    const toAccount = await this.accountRepository.findOne({
      where: { id: toId },
    });

    if (!fromAccount || !toAccount) throw new Error("Accounts not found");

    if (fromAccount.balance < amount) {
      throw new Error("Insufficient funds"); // Automatically rolls back
    }

    fromAccount.balance -= amount;
    toAccount.balance += amount;

    await this.accountRepository.save([fromAccount, toAccount]);
  }
}

Isolation Levels

import { IsolationLevel } from "typeorm/driver/types/IsolationLevel";

@Injectable()
export class InventoryService {
  constructor(
    private readonly productRepository: Repository<Product>,
    private readonly dbTransactionService: DbTransactionService,
  ) {}

  async updateStock(productId: string, quantity: number): Promise<void> {
    await this.dbTransactionService.executeInTransaction(
      { isolationLevel: "SERIALIZABLE" },
      async () => {
        const product = await this.productRepository.findOne({
          where: { id: productId },
        });
        product.stock -= quantity;
        await this.productRepository.save(product);
      },
    );
  }
}

API Reference

@Transactional()

@Transactional()
async myMethod(): Promise<void> {
  // commits automatically on success
  // rolls back automatically on error
}

@TransactionalAwareRepository(entity)

@Injectable()
@TransactionalAwareRepository(User)
export class UserRepository extends Repository<User> {
  constructor(private readonly ctx: DbTransactionContext) {
    super(User, ctx.getEntityManager());
  }
}

DbTransactionService

executeInTransaction<T>(callback: () => Promise<T>): Promise<T>
executeInTransaction<T>(options: TransactionOptions, callback: () => Promise<T>): Promise<T>

DbTransactionContext

getEntityManager(): EntityManager
getQueryRunner(): QueryRunner | undefined
isActive(): boolean
getTransactionId(): string | undefined

TransactionOptions

interface TransactionOptions {
  propagation?: boolean; // default: true
  isolationLevel?: IsolationLevel; // default: 'READ COMMITTED'
}

IsolationLevel

type IsolationLevel =
  | "READ UNCOMMITTED"
  | "READ COMMITTED"
  | "REPEATABLE READ"
  | "SERIALIZABLE";

Advanced Patterns

Testing with Transactions

describe("UserService", () => {
  let service: UserService;
  let module: TestingModule;

  beforeEach(async () => {
    module = await Test.createTestingModule({
      imports: [
        TypeOrmModule.forRoot({
          /* test db config */
        }),
        TransactionalModule,
        TypeOrmModule.forFeature([User]),
      ],
      providers: [UserService, UserRepository],
    }).compile();

    service = module.get(UserService);
  });

  it("should rollback on error", async () => {
    await expect(service.createUser("test", "invalid-email")).rejects.toThrow(
      "Invalid email",
    );

    const count = await service.countUsers();
    expect(count).toBe(0);
  });
});

Concurrent Transactions

async processBatch(items: Item[]): Promise<void> {
  await Promise.all(
    items.map(item =>
      this.dbTransactionService.executeInTransaction({ propagation: false }, async () => {
        await this.processItem(item);
      }),
    ),
  );
}

Troubleshooting

  • Ensure @Transactional() is applied.
  • Ensure repository extends @TransactionalAwareRepository.
  • Ensure errors are thrown for rollback.

Best Practices

  • Keep transactions short.
  • Don’t catch errors inside @Transactional().
  • Use propagation wisely.
  • Set timeouts.
  • Use appropriate isolation levels.

Comparison with Other Solutions

| Feature | This Package | nestjs-cls (Transactional) | Manual TypeORM | typeorm-transactional | | :--------------------- | :--------------------------------- | :-------------------------- | :------------- | :-------------------- | | NestJS Integration | ✅ Native | ✅ Plugin-based | ⚠️ Manual | ⚠️ Limited | | Setup Complexity | ✅ Minimal (Plug-and-play) | ⚠️ High (Multi-step config) | ⚠️ Moderate | ✅ Low | | Bundle Weight | ✅ Ultralight (Single-purpose) | 📦 Heavy (Full CLS Suite) | N/A | ⚠️ Moderate | | Decorator Support | ✅ | ✅ | ❌ | ✅ | | Async Context | ✅ | ✅ | ❌ | ✅ | | Active Maintenance | ✅ | ✅ | N/A | ⚠️ Archived | | TypeScript First | ✅ | ✅ | ✅ | ⚠️ |


Contributing

Contributions are welcome! Submit a PR.


License

MIT © Ankit Pradhan