How To use service methods inside typeorm transactions

4.9k Views Asked by At

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

2

There are 2 best solutions below

1
kamilg On

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 .transaction will be under single transaction.

3
Davran Sabiraliev On

If I got your question correctly, you can use @TransactionManager() entityManager?: EntityManager and pass entityManager to the services For example:

class Module3Service{
    constructor(
    private readonly module1service: Moudle1Service,
    private readonly module2service: Module2Service
    ){}

    @Transaction()
    save(@TransactionManager() entityManager?: EntityManager) {
        this.module1service.create(entityManager)
        this.module2service.create(entityManager)
    }
class Module1Service{
    save(entityManager: EntityManager) {
        entityManager.save()
    }
class Module2Service{
    save(entityManager: EntityManager) {
        entityManager.save()
    }