alphamikle / nest_transact

Simplest transactions support for Nestjs with Typeorm

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Question : Is `nest_transact` working with chain of services ?

moulinraphael opened this issue · comments

Hi :)

Thanks for this useful repo in order to improve the experience of transactions in NestJS application. Your solution is very nice in order to avoid transmitting entityManager in each services' call and also in order to avoid using Transactional Typeorm decorators which will be depreciated in the future.

However is your solution forwarding entityManager through a chain of services ?

class Controller {
  someAction() {
    return getManager().transaction((entityManager) => {
      return this.parentService.withTransaction(entityManager).someParentMethod();
  }
}

class ParentService {
  someParentMethod() {
    return this.childService.someChildMethod();
    // Do we have to use `withTransaction` here ? 
    // How to access `entityManager` ?
  }
}

class ChildService {
  someChildMethod() {
    return this.childRepo.someRepoMethod();
  }
}

Hello, @moulinraphael! See answers in comments:

class Controller {
  someAction() {
    return getManager().transaction((transactionEntityManager) => {
      return this.parentService.withTransaction(transactionEntityManager).someParentMethod();
  }
}

class ParentService {
  constructor(someRepo: Repository<Some>);

  someParentMethod() {
    return this.childService.someChildMethod();

    // Question: Do we have to use `withTransaction` here ? 
    // Answer: This method, called from your controller will be using [transactionEntityManager] from
    // the controller and all of your sub-services and their sub-services will be using this manager too
    // All of them will be recreated when you call method [withTransaction]

    // Question: How to access `entityManager` ?
    // Answer: You can simply use getter [manager] on some of your repositories, for example [this.someRepo.manager]
    // If this service called in transaction, this manager will be transactionEntityManager, if not - it will be usual manager
  }
}

class ChildService {
  someChildMethod() {
    return this.childRepo.someRepoMethod();
  }
}

Ok awesome :) I wasn't aware that the creation of a new instance of a service using a specific manager will create new instances of each sub-services with this manager, that's great