typeorm-transactional-cls-hooked icon indicating copy to clipboard operation
typeorm-transactional-cls-hooked copied to clipboard

How to commit the transaction?

Open stovberpv opened this issue 4 years ago • 4 comments

Hi there. Thx for this awesome library, but i have one question about the transactions. How to commit a transaction when using the `@Transactional () ' decorator?

@Transactional()
async myAwesomeMethod(): Promise<void> {
  await this.repository.save(...);

  // <-- how can i commit a transaction before an exception occurs? 

  throw new Error();
}

stovberpv avatar Feb 16 '21 09:02 stovberpv

I can imagine that it should be possible for the library to catch a specific Symbol being thrown.

So to commit you would do something like this:

import { ...., CommitTransaction } from 'typeorm-transactional-cls-hooked';

@Transactional()
async myAwesomeMethod(): Promise<void> {
  await this.repository.save(...);

  throw CommitTransaction;
  // <-- how can i commit a transaction before an exception occurs? 

  throw new Error();
}

koenpunt avatar Apr 06 '21 13:04 koenpunt

But then it will interrupt the execution of the function? How to make a commit without interrupting the function?

stovberpv avatar Apr 16 '21 13:04 stovberpv

I handle these cases with this pattern:

@Transactional()
async myAwesomeMethod(): Promise<void> {
  await this.runAndCommit();

 // now you can throw an error without worry of transaction is not being commited.
  throw new Error();
}

// requires new in propagation forces the lib to create another transaction
@Transactional({ propagation: Propagation.REQUIRES_NEW })
async runAndCommit(): Promise<void>{ 
  // do your things and after this method runs, the transaction is commited
  // even if this method is called by a method wrapped by another transaction.

  await this.repository.save(...);
}

H4ad avatar Aug 10 '21 20:08 H4ad

@H4ad case worked for me.

Just needs to remember to set in the case we really need.

Beloin avatar Sep 16 '21 13:09 Beloin