1.1.5 • Published 3 years ago
@usevisitor/with-sequelize-transaction v1.1.5
@usevisitor/with-sequelize-transaction
This module was created to automatically create transactions and rollaback to prevent unwanted side-effects in your code.
Used to pass a sequelize transaction to any function or controller and then it handles automatic rollbacks on fail.
Install:
yarn add '@usevisitor/with-sequelize-transaction'
Example:
import {initWithTransaction} from '@usevisitor/with-sequelize-transaction';
const sequelize = new Sequelize(....);
export const withTransaction = initWithTransaction(sequelize); // ideally do this only once where you init Sequelize and export it
....
export const createAndGetAllProductsHandler = withTransaction(transaction: Sequelize.Transaction => async (req, res) => {
// Inside this function the transaction will be automatically rolled back
// and the Sequelize error thrown to an upper middleware to be handled
const {product, user} = req.body;
await ProductModel.create(product, {transaction});
await UserModel.create(user, {transaction});
const products = ProductModel.findAll({transaction});
res.json({
products,
user,
});
});