odavid / typeorm-transactional-cls-hooked

A Transactional Method Decorator for typeorm that uses cls-hooked to handle and propagate transactions between different repositories and service methods. Inpired by Spring Trasnactional Annotation and Sequelize CLS
MIT License
522 stars 86 forks source link

transaction w/o class method decorator #92

Open lytc opened 3 years ago

lytc commented 3 years ago

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 commented 3 years ago

Hi,

PR will be reasonable...

Cheers

Glench commented 2 years ago

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