nestjs / typeorm

TypeORM module for Nest framework (node.js) 🍇

Home Page:https://nestjs.com

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Better transaction management

Faithfinder opened this issue · comments

I'm submitting a...


[ ] Regression 
[ ] Bug report
[x] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

Currently working with transactions is a pain and doesn't play well with using DI with repositories, because you need to get the repositories from transactional entity manager and as a consequence pass the manager around everywhere.

Proposal

As I was looking for a better way to manage transactions I came across this library: https://github.com/odavid/typeorm-transactional-cls-hooked
However it seems that the creator of it is now too busy to really maintain it. So I thought that maybe you'd want to take it under your wing, or reimplement something similar for your own purposes like you did with type-graphql.

We don't plan to add more features on top of typeorm. You can try reporting this issue in the typeorm repository instead.

I'll try, but I think it's a non-issue from the point of view of typeorm. From the point of view of typeorm you're getting the repositories manually anyway, using getRepository, and can even do that with getManager().getRepository(). It should be simple enough to structure code in a way that uses transactional entity manager in some cases. While having to pass a manager around is not ideal, my main issue lies at the boundary of typeorm and Nest DI.

I'd argue that using DI to inject repositories with nest is inadvisable without better way to work with transactions. Any even mildly complicated system needs transcations at some point. A transactional method can't use injected repositories. So you're either using two paradigms around the codebase - this.somethingRepo for non-transactional and transactionalEntityManager.getRepository(Something) for transactional - which is confusing, or you're dropping the DI alltogether and structure all your logic around entity manager, giving all your code that's working with database another parameter.

I do want to use DI! It makes the code look quite nice. But I really don't like to introduce a second way to structure the code

Take a look at this blog post: https://aaronboman.com/programming/2020/05/15/per-request-database-transactions-with-nestjs-and-typeorm/

It explains how to use the power of the Nest DI system to implement cross-service transactions.