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

transaction w/o class method decorator #92

Open
lytc opened this issue Mar 24, 2021 · 2 comments
Open

transaction w/o class method decorator #92

lytc opened this issue Mar 24, 2021 · 2 comments

Comments

@lytc
Copy link
Contributor

lytc commented Mar 24, 2021

Firstly, thank for your awesome lib @odavid !

In our current project we're on the way to use this lib to resolve some issues which we're facing with TypeORM core transaction. But we found that this lib just supported class method decorator. I implemented two helpers that can help to run transaction in the middle of the method/function body or wrap the a function that will run in transaction

import { Transactional } from 'typeorm-transactional-cls-hooked';

export class TransactionRunner {
  @Transactional()
  static run<Func extends (this: any, ...args: any[]) => ReturnType<Func>>(fn: Func) {
    return fn();
  }
}

export function wrapInTransaction<Func extends (this: any, ...args: any[]) => ReturnType<Func>>(
  fn: Func
): Func {
  function wrapped(this: unknown, ...newArgs: unknown[]): ReturnType<Func> {
    return TransactionRunner.run(() => fn.apply(this, newArgs));
  }

  return wrapped as Func;
}

Then we can use it like this:

function myService() {
  // do something here, e.g. call external service to get data
  ....
  TransactionRunner.run(() => {
    ....
  })
}

Or wrap a function:

function myService() {
 // do something
 .....
}
export default wrapInTransaction(myService);

But the problem is that I couldn't found a way to pass Propagation and Isolation option to these functions. Is there any suggestion or it's reasonable to create a new PR that will extract the logic from Transactional.ts?

@odavid
Copy link
Owner

odavid commented Mar 28, 2021

Hi,

PR will be reasonable...

Cheers

@Glench
Copy link

Glench commented Jan 11, 2022

I think this can be closed now that the PR was merged, although this should probably be documented in the README.

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

3 participants