How should I refactor my transactions?
Hi, I wondering how I should refactor my code. Right now I have forms in which data affects multiple tables and its relations and I use a transaction to make sure data consistency when adding or updating.
I'd like to split the transaction into different functions and even different files. I was thinking I could simply send my transaction object to the function but I don't like this approach since the query function then is dependent on receiving the transaction object. In case I don't need the query to be in a transaction I could send the transaction object (tx) as optional and then check and execute tx.query or db.query, but I don't like this approach.
So I am asking, is there a more elegant solution to split my transaction queries into different files and functions?
Thank you!
5 Replies
https://github.com/vkondratiuk482/propagated-transactions Maybe this approach is more to your liking? It would save you adding a new function parameter but its kind of verbose too. But maybe it suits your more than your current solution (which I would prefer)
GitHub
GitHub - vkondratiuk482/propagated-transactions: Library that provi...
Library that provides a wrapper to propagate and manage database transactions - vkondratiuk482/propagated-transactions
yup, I don't like it either... ☹️
Hey uri,
I have figured out a waaaaaay better solution, without you needing to pass any parameter to functions. You would just have to add a @Transactional() Decorator to the root function as of which every database call should be run in a transaction. Are you still looking for a solution?
@uri
This would also work for nested db calls. So for example: Imagine a function A() that calls B() and C(). Both in B() and C() there are database calls. If you annotate A() with @Transactional() you would still have the db calls in B() and C() in the same transaction
Thank you, I'll take a look. I ended up sending the transaction as parameter and wasn't that bad
Are you using Nestjs?
With NestJS its extremly easy
I will set up a sample project for you. Ill let you know once I set it up. I will set it up using Nestjs but the principle is applicable to any other app ofc