Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to commit the transaction? #87

Open
stovberpv opened this issue Feb 16, 2021 · 4 comments
Open

How to commit the transaction? #87

stovberpv opened this issue Feb 16, 2021 · 4 comments

Comments

@stovberpv
Copy link

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();
}
@koenpunt
Copy link

koenpunt commented Apr 6, 2021

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();
}

@stovberpv
Copy link
Author

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

@H4ad
Copy link

H4ad commented Aug 10, 2021

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(...);
}

@Beloin
Copy link

Beloin commented Sep 16, 2021

@H4ad case worked for me.

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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

4 participants