Trung BìnhNestJS iconNestJS

Transactions trong TypeORM với NestJS — cách implement đúng?

Transactions đảm bảo multiple DB operations thành công hoặc rollback toàn bộ.

Cách 1 — QueryRunner (recommend cho complex transactions):

typescript
const queryRunner = this.dataSource.createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();
try {
  await queryRunner.manager.save(User, user);
  await queryRunner.manager.save(Profile, profile);
  await queryRunner.commitTransaction();
} catch (err) {
  await queryRunner.rollbackTransaction();
  throw err;
} finally {
  await queryRunner.release();
}

Cách 2 — EntityManager.transaction() (cleaner cho simple cases):

typescript
await this.dataSource.transaction(async manager => {
  await manager.save(User, user);
  await manager.save(Profile, profile);
  // Tự động rollback nếu throw
});

Cách 3 — @Transaction decorator (deprecated trong TypeORM 0.3+, không dùng).

Pitfall: không mix repository từ DI và queryRunner.manager trong cùng transaction — chúng dùng connection pool khác nhau.

Xem toàn bộ NestJS cùng filter theo level & chủ đề con.

Mở danh sách NestJS