🦅 NestJS Intermediate

How do you handle database transactions in NestJS with TypeORM?

Answer

Database transactions ensure a group of operations all succeed or all fail atomically. In NestJS with TypeORM, use the data source's transaction() method: await this.dataSource.transaction(async (manager) => { const user = await manager.save(User, userDto); await manager.save(Order, { userId: user.id, ...orderDto }); });. The transaction manager (manager) is the entity manager scoped to this transaction — use it for all operations that should be atomic. If any operation throws, the entire transaction is rolled back. For declarative transactions, use the @Transactional() decorator from the typeorm-transactional package, which uses AsyncLocalStorage to propagate the transaction context automatically through the call stack.