Skip to content

Instantly share code, notes, and snippets.

@AlfieriChou
Last active January 16, 2021 02:53
Show Gist options
  • Save AlfieriChou/9c607cf79fb126b3ed201b21bb10192c to your computer and use it in GitHub Desktop.
Save AlfieriChou/9c607cf79fb126b3ed201b21bb10192c to your computer and use it in GitHub Desktop.
sequelize.transaction.js
const transaction = async () => {
let trx = await sequelize.transaction()
try{
const user = await User.create({
first_name: 'wwang',
last_name: 'ahahaha'
}, {trx})
const updateResult = await User.update({
first_name: 'wang'
}, {
where: {id: user.dataValues.id}
}, {trx})
await trx.commit()
} catch (err) {
await trx.rollback(new Error('something went wrong'))
}
}
@AlfieriChou
Copy link
Author

// 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

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