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 });
}
});
@ljinke
Copy link

ljinke commented Feb 22, 2018

transaction would always be undefined in catch block?

@hoangbits
Copy link
Author

@ljinke: it's just updated.:))

@ashish8833
Copy link

@legiahoang
I am using the same thing for my project, first create the user and then after creating a role for that, I am defined the relationship in the database as well. in my case user still in the database, is it possible for delete that user entry?

@flue89
Copy link

flue89 commented May 16, 2019

Really fine method 👍

@vutrans159951
Copy link

you should move this
Model.destroy({where: {id}}, {transaction});
to
Model.destroy({where: {id}, transaction}); since destroy function only take 1 parameter according to
http://docs.sequelizejs.com/class/lib/model.js~Model.html#static-method-destroy

@rajeshcdn
Copy link

@legiahoang hello I am using same method inside to async.waterfall but is not working so please provide me any solution.

router.post('/upload',async function(req, res){

const transaction =  await db.sequelize.transaction();

try {	
	var ArrayData =[];
	var branchId =0;
	async.waterfall([
	   function getDBZoneList(done) {
			models.ZoneList.findAll({
				where:{
					 status: 1
				}
			}).then(function(ZoneList) {
				migrationDataArray.push(ZoneList)
				done(null, ArrayData);
			});	
	   },
	   function setBranches(ArrayData,done) {
			models.Branch.create({
					name: "Test Branch1",
					status: 1,
				},transaction).then(function(insertData) {
						branchId= insertData.id;
						
						var subbranch =[{
							name: "Sub Branch2",
							parentId: branchId,
							status: 1,
						},{
							name: "Sub Branch3",
							parentId: branchId,
							status: 1,
						}];
						
						models.Branch.bulkCreate(subbranch,transaction).then(function(insertData) {
							done(null, ArrayData);
						});
				})   
	   },
	    function setLabels(ArrayData,done) {
			models.Label.create({
					name: "Test Label",
					branchId:branchId
					status: 1,
				},transaction).then(function(insertData) {
						branchId= insertData.id;
						
						var subLabel =[{
							name: "Sub Label2",
							branchId: branchId,
							status: 1,
						},{
							name: "Sub Label3",
							branchId: branchId,
							status: 1,
						}];
						
						models.Label.bulkCreate(subLabel,transaction).then(function(insertData) {
							done(null, ArrayData);
						});
				})   
	   }],						
	   function(err,ArrayData) {
			if(err){
				await transaction.rollback();
				res.json({ success: 0, message: "error" });
			}else{
				await transaction.commit();
				res.json({ success: 1, message: "Success",data:ArrayData });
			}
	   });
catch (ex) {
	await transaction.rollback();
	res.json({ success: 0, message: "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