Skip to content

Instantly share code, notes, and snippets.

@hoangbits
Last active September 22, 2020 00:42
Show Gist options
  • Save hoangbits/ec0efbde0e4d484f16516e2bd81edd3e to your computer and use it in GitHub Desktop.
Save hoangbits/ec0efbde0e4d484f16516e2bd81edd3e to your computer and use it in GitHub Desktop.
using await with transaction in sequelize ORM
// get transaction
const transaction = await sequelize.transaction();
try {
// step 1
await Model.destroy({where: {id}}, {transaction});
// step 2
await Model.create({}, {transaction});
// commit
await transaction.commit();
} catch (err) {
// Rollback transaction if any errors were encountered
await transaction.rollback();
}
https://stackoverflow.com/questions/42870374/node-js-7-how-to-use-sequelize-transaction-with-async-await/43342688#43342688
router.route('/').post(async (req, res) => {
const transaction = await db.sequelize.transaction();
try {
let employee = await models.tbl_employees.create(req.body, {
transaction
});
// let role_id = req.body.role_id;
// let employee_id = employee.employee_id;
// let user_role_obj = {
// employee_id,
// role_id
// };
let user_role = await models.tbl_user_role.create(user_role_obj, {
transaction
});
await transaction.commit();
// if (employee) {
// res.json({
// success: 1,
// data: employee,
// message: messagesList.addEmployee.success
// });
// }
} catch (ex) {
await transaction.rollback();
res.json({ success: 0, message: messagesList.addEmployee.error });
}
});
@cjancsar
Copy link

This does not seem to work any longer as destroy has multiple options...

@herudi
Copy link

herudi commented Mar 28, 2020

maybe

let transaction;
try {
 // get transaction
  transaction = await sequelize.transaction();

  // step 1
  await Model.destroy({where: {id}}, {transaction});

  // step 2
  await Model.create({}, {transaction});

  // commit
  await transaction.commit();

} catch (err) {
  // Rollback transaction if any errors were encountered
  if(transaction){
      await transaction.rollback();
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment