Search code examples
transactionsnestjstypeorm

TypeOrm transaction with method in other service


I used typeorm with nestjs. but i don't know how to use transaction with method

for example,

async createTrack(track) {
try {

  const createdTrack = await this.createTrack(track);

  //this.boardService.createBoard will work by transaction.
  const board = await this.boardService.createBoard({
      ...track.board
  });

  return board;
} catch (e) {
  throw e;
}

i wanna use method of boardSerivce with trasaction.

how to do?


i solved it.

try it. TypeORM transaction with query builder

or

use https://github.com/odavid/typeorm-transactional-cls-hooked


Solution

  • Did you check the docs? https://docs.nestjs.com/techniques/database#transactions

    Copy from the docs above

    const queryRunner = this.connection.createQueryRunner();
    
      await queryRunner.connect();
      await queryRunner.startTransaction();
      try {
        await queryRunner.manager.save(users[0]);
        await queryRunner.manager.save(users[1]);
    
        await queryRunner.commitTransaction();
      } catch (err) {
        // since we have errors lets rollback the changes we made
        await queryRunner.rollbackTransaction();
      } finally {
        // you need to release a queryRunner which was manually instantiated
        await queryRunner.release();
      }