Reputation: 1352
Trying to figure out the right way to use Sequelize transactions in expressjs. The following code finds a post by id increments the reply count in the post table, updates the post and then creates a reply in the reply table. Trying to call the code in a controller action and it does not work. The internal promises are not being hit. Any suggestions on the right way to use the transactions in Sequelize?
Sequelize.transaction(function (t) {
db.Post.find({where:{id: postId}}, {transaction:t}).then(function(post)
{
var count = post.reply + 1;
post.update({replyCount:count},{transaction:t});
db.Reply.create(replyData, {transaction:t}).then(function(newcomment, created){
res.json(newcomment);
});
});
}).then(function (result) {
// Transaction has been committed
// result is whatever the result of the promise chain returned to the transaction callback
}).catch(function (err) {
// Transaction has been rolled back
// err is whatever rejected the promise chain returned to the transaction
});
});
Upvotes: 2
Views: 910
Reputation: 830
There's no value in the initial .find() being in the transaction. There's nothing to undo in the case of a rollback. Only writes or updates need to be rolled back in a transaction. The try/catch will deal with any of the queries failing and a rollback will be automatically triggered for the transaction items.
Consider this more modern ES6 solution:
try {
const result = await sequelize.transaction(async (t) => {
// no need to include this in the transaction, it only reads (find)
const post = await db.Post.find({where:{id: postId}});
const count = post.reply + 1;
const updateResult = await post.update({
replyCount: count
}, { transaction: t });
// i guess you want to use result in here to create replyData
const createResult = await db.Reply.create({
replyData,
}, { transaction:t });
return res.json(newcomment);
});
} catch (error) {
// If the execution reaches this line, an error occurred.
// The transaction has already been rolled back automatically by Sequelize!
}
Reference: - https://sequelize.org/master/manual/transactions.html#managed-transactions
Upvotes: 0
Reputation: 1593
Sequelize.transaction(function (t) {
return db.Post.find({where:{id: postId}}, {transaction:t}).then(function(post)
{
var count = post.reply + 1;
return post.update({replyCount:count},{transaction:t})
.success(result =>
// i guess you want to use result in here to create replyData
return db.Reply.create(replyData, {transaction:t})
.then(function(newcomment, created){
return res.json(newcomment);
});
);
});
Upvotes: 2