Setup
I have a Express server in typescript
and i am using PostgreSQL as database with the package pg to handle db query
Goal
I want keep any request in a single transaction
I can execute BEGIN; at the start of any request.
But after the request ends I want to execute COMMIT;.
If something failed I want to execute ROLLBACK;.
Also COMMIT; will be executed only for POST, PUT or DELETE requests.
What would be the best approach to implemented these ?
Progress
I have added a middleware that can initiate a db transaction i.e. executing BEGIN;.
Added a middleware that would set the db client object in request object. So it (db) can be accessed in any router.
Also added a error handler that would handle any error and execute ROLLBACK;
for the commit, only solution I could think is to create custom send and json function and use that instead of res.send and res.json and execute COMMIT; at the end of these function