nestjs / TypeOrm database transaction

后端 未结 4 1570
遥遥无期
遥遥无期 2021-01-12 13:45

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
4条回答
  •  不要未来只要你来
    2021-01-12 14:02

    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.

提交回复
热议问题