LoginSignup
1
0

More than 3 years have passed since last update.

typeormのTransactionデコレーターの引数に関するメモ

Last updated at Posted at 2019-12-05

NestJSでの実装の話。
引数を取らないメソッド(hogeMethod)では以下のようにthis.entityManagerを別メソッドに渡して利用できていたのだが

@Injectable()
export class HogeService {
  constructor(@InjectEntityManager('db_name') private readonly entityManager: EntityManager) {}

  @Transaction('db_name')
  async hogeMethod() {
    const result = await getHoge(this.entityManager);
  }
}

以下のようにメソッドが引数を受け取るように定義をしたところthis.entityManagerが利用できなくなってしまった。

@Injectable()
export class HogeService {
  constructor(@InjectEntityManager('db_name') private readonly entityManager: EntityManager) {}

  @Transaction('db_name')
  async hogeMethod(pamar1: string) {
    const result = await getHoge(this.entityManager);
  }
}

以下typeormのドキュメント
https://github.com/typeorm/typeorm/blob/master/docs/transactions.md#transaction-decorators

どうやらTransactionデコレーターを利用する際はTransactionManagerをProvideしないといけないみたい。
メソッドが引数を受け取らない定義の時はおそらくよろしく処理してくれていたのかな。

なので修正後は以下のように定義した。

@Injectable()
export class HogeService {
  constructor(@InjectEntityManager('db_name') private readonly entityManager: EntityManager) {}

  @Transaction('db_name')
  async hogeMethod(
    param1: string,
    @TransactionManager() entityManager?: EntityManager,
  ) {
    const result = await getHoge(entityManager);
  }
}

こうすることでエラーが発生しなくなった。
entityManagerをOptionalとすることで利用する際に引数を省略できる。

const result = await hogeMethod('pamar string!!!');

地味に4時間くらいハマった・・・。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0