nestjs / TypeOrm database transaction

扶醉桌前 提交于 2019-12-01 22:59:15

问题


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.


回答1:


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.




回答2:


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!



来源:https://stackoverflow.com/questions/53680665/nestjs-typeorm-database-transaction

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!