DEV Community

Cover image for Coding Unmanaged and Managed Transactions with NodeJS, Express and Sequelize
Luiz Calaça
Luiz Calaça

Posted on

Coding Unmanaged and Managed Transactions with NodeJS, Express and Sequelize

Hi, Devs!

We have two types of transactions using Sequelize: unmanaged and managed transactions.


Wha is transaction on persistence layer?

A transaction is a small unit of a sotfware and it may contain several chunks that are tasks to be commited to the database just all together and could garantee Atomicity, Consistency, Isolation, and Durability.

Example: When we make a bank transfer transaction, we need it to be debited from our account and credited to another. You can't just do one or the other.

Transaction

Unmanaged Transactions

Unmanaged transactions means that committing and rolling back the transaction should be done manually by the user (by calling the appropriate Sequelize methods).

//Unmanaged transactions

const express = require('express')
const { User, Product } = require('../models')
const router = express.Router()

// ...
router.post('/userBook', (request, response) => {

  const transaction = await sequelize.transaction()

  try {
    const { name, username, nameBook 
           description, price }= request.body;

    const newBook = Book.create(
      { nameBook, description, price },
      { transaction: transaction }
    );

    const userProduct = Product.create(
      { name, userName, price, newBook.id },
      { transaction: transaction }
    );

    await transaction.commit()

    response.status(200).json({message: 'Success'})
  } catch (error) {
    await transaction.rollback()
    response.status(500).json({ message: 'Wrong' })
  }  
});
Enter fullscreen mode Exit fullscreen mode

Managed Transactions

Managed transactions handle committing or rolling back the transaction automatically. You start a managed transaction by passing a callback to sequelize.transaction

// Managed Transactions

const express = require('express')
const { User, Product } = require('../models')
const router = express.Router()

// ...
router.post('/userBook', (request, response) => {
  try {
    const { name, username, nameBook 
           description, price }= request.body

    await sequelize.transaction(async (t) => {

      const newUser = User.create({ name, username})

      const userProduct = Product.create(
      { nameBook, description, newUser.id })

      response.status(200).json({message: 'Success'})
      })
  } catch (error) {
    response.status(500).json({ message: 'Wrong' })
  }  
})
Enter fullscreen mode Exit fullscreen mode

See you soon!

Contacts
Email: luizcalaca@gmail.com
Instagram: https://www.instagram.com/luizcalaca
Linkedin: https://www.linkedin.com/in/luizcalaca/
Twitter: https://twitter.com/luizcalaca

Top comments (0)