Support transaction per request with TypeORM
See original GitHub issue
[x] Feature request
What is the motivation / use case for changing the behavior?
We would like to make all TypeORM database operations during a certain request/endpoint transactional. Based on https://github.com/typeorm/typeorm/issues/404#issuecomment-295855913 we could create a transactional entity manager and pass it around to all our services, but that doesn’t feel very nestjs like. More recently @pleerock suggested the use of scoped services
in https://github.com/typeorm/typeorm/issues/1895#issuecomment-380556498 which would enable a transaction-per-request and use the same transaction manager instance across all services without having to pass it around. A concrete example is in this doc.
Are scoped services
something that the nestjs team has thought about implementing?
Is there a better way of handling TypeORM transactions in nestjs? Keeping in mind that custom repositories should not be singleton services and it is likely transaction decorators will be removed from TypeORM core.
For example:
UserController.ts
@Controller("/user")
export class UserController {
constructor(
private userService: UserService,
) {}
@Post("/")
@Transaction()
async createNewUser(@Body() body: UserDTO) {
return await this.userService.createNewUser(body);
}
}
UserService.ts
@Component()
export class UserService {
constructor(private userRepository: UserRepository) {}
async createNewUser(userDTO: UserDTO): Promise<User> {
const user = new User();
user.username = userDTO.username;
...
const saved = await this.userRepository.save(user);
await this.userRepository
.createQueryBuilder()
.relation(User, "departments")
.of(saved)
.add(userDTO.departmentIds);
return saved;
}
}
Where the dependency injected userRepository
automagically is using the transactional entity manager under the hood.
Issue Analytics
- State:
- Created 5 years ago
- Reactions:15
- Comments:12 (2 by maintainers)
Top GitHub Comments
Hi All, I’ve created a small project that adds a Spring Style Transactional Decorator and can control propagation. See https://github.com/odavid/typeorm-transactional-cls-hooked
Hope this helps, Ohad
We’ll get back to this feature once
async-hooks
functionality moves into stable API.