I have read about transactions in typeorm.
@Transaction()
save(user: User, @TransactionRepository(User) userRepository: Repository<User>) {
return userRepository.save(user);
}
I have a nestjs application with multiple modules and services. what i need to do is call different service methods inside a transaction. but @TransactionRepository provides me with the repository. So what should i do to achieve a transaction with multiple service methods being called inside it. like
class Module3Service{
constructor(
private readonly module1service: Moudle1Service,
private readonly module2service: Module2Service
){}
@Transaction()
save() {
this.module1service.create()
this.module2service.create()
}
I don't know how to achieve it. and also correct me if I am wrong that a possible solution is to change the moduleservice dependencies ( module1service dependency => module1repositoroy) to change to our new repository instance that we get from @TransactionRepository(Module1Enity) module1repository: Repository<Module1Entity> inside the tranction method. or any other solution please help
I am using postgres
You will have trouble with
@Transaction()during unit tests.I would recommend Typeorm's manager
getManager().transaction( () => { ... } )which does not require specific repository. Everything that is executed within callback provided to.transactionwill be under single transaction.