Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nestjs / TypeOrm database transaction

Tags:

typeorm

nestjs

Assuming we have 2 services, A and B. Service A has a function doing the following:

  1. Validate the data
  2. Call a service B function, that makes changes to the database
  3. Do some more stuff
  4. Do changes to the database

Now, let's assume that one of the following, steps 3 or 4 failed. Since service B made changes in the database, those changes are still there.

Is there any way of rolling the database back in this case? I though about database transactions, but I couldn't find any way to do that in nest js, although it is supported by TypeOrm, it doesn't look natural to nest. If not, I am now "stuck" with the changes occured by service B, but without the changes should have happen by A.

Thanks a lot.

like image 939
superuser123 Avatar asked Dec 08 '18 07:12

superuser123


People also ask

Which database is best for NestJS?

Nest uses TypeORM because it's the most mature Object Relational Mapper (ORM) available for TypeScript. Since it's written in TypeScript, it integrates well with the Nest framework.

What databases does TypeORM support?

TypeORM is a TypeScript ORM (object-relational mapper) library that makes it easy to link your TypeScript application up to a relational database database. TypeORM supports MySQL, SQlite, Postgres, MS SQL Server, and a host of other traditional options.


2 Answers

Many solutions are available, they should all be based on SQL transaction management.

Personally I feel that the simplest way to achieve that is to use the same EntityManager instance when you execute code on your database. Then you can use something like:

getConnection().transaction(entityManager -> {
    service1.doStuff1(entityManager);
    service2.doStuff2(entityManager);
});

You can spawn a QueryRunner from an EntityManager instance that will be wrapped in the same transaction in case you execute raw SQL outside ORM operations. You need also to spawn Repository instances from EntityManager as well or they will execute code outside the main transaction.

like image 90
zenbeni Avatar answered Sep 29 '22 00:09

zenbeni


Here is how I solved it since I needed to use a pessimistic lock.

I feel it is the "Nest" way of doing things as you can simply ask NestJS to inject an instance of a Typeorm Connection and you're good to go.

@Injectable()
class MyService {
  // 1. Inject the Typeorm Connection
  constructor(@InjectConnection() private connection: Connection) { }

  async findById(id: number): Promise<Thing> {
    return new Promise(resolve => {
      // 2. Do your business logic
      this.connection.transaction(async entityManager => {
        resolve(
          await entityManager.findOne(Thing, id, {
            lock: { mode: 'pessimistic_write' },
          }),
        );
      });
    });
  }
}

Simply place whatever other logic you need inside the .transaction block and you're good to go.

NOTE: You MUST use the entityManager provided by the .transaction method or else it will not work.

like image 27
nathanl93 Avatar answered Sep 29 '22 02:09

nathanl93