DEV Community

Cover image for NestJS + TypeORM Transaction
Vincent Jang
Vincent Jang

Posted on • Updated on

NestJS + TypeORM Transaction

Few weeks ago, I started a new personal project for daily-pattern, I encountered a problem about transaction. It was a severe problem for me. I can't remember a specific version of Typeorm is, but they deprecated a getConnection() method in new version I installed. So I choiced downgrade Typeorm version and use the way I used to.

But, my used way has a tiny(but severe) trouble,
let see a code below.

const queryRunner = getConnection().createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();

try {
  // ...
  await this.modelRepository.save(newOBj);
  await queryRunner.commitTransaction();
} catch(e) {
  // error control logic
}

Enter fullscreen mode Exit fullscreen mode

Can you see a problem?
It was totally stupid.
I thought that QueryRunner observes the DB's CUD action and makes it a transaction when it occurs.

But, It was not.
So I change code like this.

const queryRunner = getConnection().createQueryRunner();
await queryRunner.connect();
await queryRunner.startTransaction();

try {
  // ...
  await querRunner.manager.save(newObj);
  await queryRunner.commitTransaction();
} catch(e) {
  // error control logic
}

Enter fullscreen mode Exit fullscreen mode

It seems like, There is an object called manager in QueryRunner, and this object determines the table according to the model and makes it a transaction.

a new logic work properly, so I just want to note my mistake and improvement. For me, and for someone who having the same problem as me.

Thanks for reading.
Plz comment if you have more nice idea or solution.


Ref --
Cover Img ref : https://miro.medium.com/max/1400/1*GafbQWGfs0xDuH_A0z08wg.png

Top comments (0)