Answer the question
In order to leave comments, you need to log in
How to properly organize work with transactions in a nodejs project?
There is a service API project on NodeJS and a database on Postgres. It uses action models: i.e. each model is responsible for an indivisible entity. But when working, it turns out that operations with the database (insert, update, delete) need to be wrapped in a transaction in the database, and according to the logic of work, it turns out that there can be several such operations from different models.
Example
When changing personal data in the application, 2 models are used: the user model and the model for logging user actions. The user model changes the data itself, and the logging model makes a corresponding record of the changes. Accordingly, this is a single transaction for the database, and if at least one of the actions fails, then the entire transaction should be canceled. Working with transactions is based on the complete isolation of transactions from each other, i.e. no read commited or dirty reads. When working with a database, a db object is added to each model, which is a link to the pool. In order for transactions to work correctly in the database, all actions must occur within the framework of one connection allocated from the pool.
Approximate construction of logic in the route using the example of Promise:
-> Check data
then-> start transaction
then-> send change request to database (user model)
then-> send request to database to log action (log model)
catch-> cancel transaction, log error
then-> commit transaction
then -> ...
Actually, the problem is to leave pool models to work with the database, but to organize work with connections correctly. The service is an API service - accordingly, it has routes and other attributes of a web application. Initially, I intended to initialize one connection to the database during a web request, i.e. abandon the pool implementation. And pull this connection to all models through a parameter in the function. But I think this is wrong and crutch. Putting the require of the module in the route, and there it is already decided whether we are working within the framework of the pool or connect - it also somehow does not shine with elegance. Among the "best practices" I also did not find this, although I may have searched little or not there.
How is it better, more elegant?
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question