How to use transactions in Typeorm with typeorm-transactional-cls-hooked

Viewed 1357

I can't get everything to run within the same transaction.

I have the following code:

export class TestService {
  repository: any;
  constructor(
  @Inject(TENANT_CONNECTION) private connection)
  {
    this.repository = connection.getRepository(Test)
  }`

 @Transactional()
  async agregar(tableNew: Test): Promise<Number> {
    const tableSave = this.repository.create(tableNew)
    await this.repository.save(tableSave)
    if(tableSave.default){
      await this.repository.update(
            {default:true,id:Not(tableSave.id)},
            {default:false}
      )
    }
    return tableSave.id 
}

The following is executed in the database:

query: START TRANSACTION
query: SELECT `Test`.`id` AS `Test_id`,`Test`.`default` AS `Test_default` FROM `test` `Test` WHERE `Test`.`id` IN (?) -- PARAMETERS: [0]
query: START TRANSACTION
query: INSERT INTO `test`(`id`,`default`) VALUES (?,?) -- PARAMETERS: [0,1]
query: COMMIT
query: UPDATE `test` SET `default` = ? WHERE (`default` = ? AND `id` != ?) -- PARAMETERS: [0,true,41]
query: COMMIT

As you can see, 2 transactions are executed, I need it to be only one

2 Answers

if you want to only start 1 transaction across multiple service, Make main service like this @Transactional(), and sub service's propagation option @Transactional(propagation: Propagation.MANDATORY). MANDATORY option will support main transaction

Related