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.
Previous
What is event-driven architecture in NestJS using the EventEmitter?
Next
What is NestJS GraphQL module?
More NestJS Questions
View all →- Intermediate How does NestJS dependency injection scoping work?
- Intermediate What are NestJS microservices and what transports are supported?
- Intermediate What is the ExecutionContext in NestJS?
- Intermediate How do you implement role-based access control (RBAC) in NestJS?
- Intermediate What is the Reflector in NestJS and how is it used?