I am using Sequelize Transactions. I want to understand how to we handle transactions when we do a function call and in the called function we do a few more Transactions.
In case of any issue, all the transactions including the ones in the called Function should be rolled back.
I am currently passing transactions as a parameter in the function call.
Is it the Right way? I couldn't find anything related to it in Sequelize documentation too.
Passing the transaction to the function should work fine as long as you catch errors from that function wherever you called the function so you can rollback the transaction if necessary.
const helperFunction(transaction) {
// do something with transaction here
// do NOT catch error here
// No need to return Transaction
}
async function main() {
let transaction;
try {
transaction = await sequelize.transaction();
await helperFunction(transaction);
await transaction.commit();
} catch(err) {
if (transaction) await transaction.rollback();
// continue handling error
}
}
You can also just define those functions within the scope of our transaction so you don't have to pass it. For example:
async function main() {
let transaction;
const helperFunction() {
// do something with transaction here
// do NOT catch error here
}
try {
transaction = await sequelize.transaction();
await helperFunction();
await transaction.commit();
} catch(err) {
if (transaction) await transaction.rollback();
// continue handling error
}
}