Member-only story
Sequelize Transactions in Node.js/Express REST API
Background
I have implemented a particular REST API with Spring-boot, and I am implementing same API endpoints in Node.js/Express/Sequelize. The concept of Transaction in Sequelize is pretty old-fashioned although it gives the desired granular control over transactions so control can be established.
Prerequisite
I assume that you are familiar with backend development in Express. This is an ecommerce backend and I will be implementing Create Order endpoint. A customer creates an order when they are done filling the Shopping Cart with items they want to buy. So we have implemented Create Customer, Shopping Cart endpoints and this API uses JWT authentication implemented with Passport.js.
Sequelize Transaction
Transaction are used to control series of database operations that we want as a persistence unit. In this case, it is a simple CRUD operation where we want to create order and orderdetail. However, they must be persisted together. Order is created and saved first, and then order details. If order details fails, order created should be rolled back.
Concepts
Sequelize transaction can be done in a few ways. Managed and unmanaged are two of it. From Sequelize documentation. Managed transactions use promise chains and returns promises to the transaction object, if all promises are resolved, commit is called. If any is rejected, rollback is…