nestjs / TypeOrm database transaction

后端 未结 4 1585
遥遥无期
遥遥无期 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 13:51

    In this case, you have to use the same transaction manager for both database operations. Unfortunately, I do not have an example repository, but I have found a potential solution using Continuation Local Storage (CLS) in Node:

    https://github.com/typeorm/typeorm/issues/1895

    This applies to Express.js, but you can create an instance of TransactionManager (for example, in a nest middleware) and store it per each request context. You then will be able to re-use this transactional manager across your service method calls, provided they are annotated with the @Transaction decorator implementation in the link above.

    If there are no errors in your function chain, the transaction manager will commit all the changes made. Otherwise, the manager will roll back any changes.

    Hope this helps!

提交回复
热议问题