I am trying to implement a transaction in Node.js (Sails.js) with Postgresql and Sails Waterline.js ORM.
I tried to adapt this answer. In that answer we have only one table. In my problem I have 2 tables which have to be locked till the transaction is over.
What should this code do:
- find User with
:Id - if this
User.coins > 0:- Update
User.coins = 0 - Create a new record in the table MyTransaction
- Update
But the snippet doesn't lock the transaction over both tables:
try {
// Start the transaction
sails.models.user.query("BEGIN", function (err) {
if (err) {
throw new Error(err);
}
// Find the user
sails.models.user.findOne(currentUser.id).exec(function (err, user) {
if (err) {
throw new Error(err);
}
if (user.coins > 0) {
var params = {
user_id: req.session.passport.user,
publicAddress: bitcoin_address,
amount: user.coins,
wohnAdresse: wohnAdresse
}
// Update the user balance
user.coins = 0;
// Save the user
user.save(function (err) {
if (err) {
throw new Error(err);
}
sails.models.myTransaction.create(params).exec(function (err, transaction) {
if (err) {
payout = {success: false};
payout.transactionError = err;
console.log("ROLLBACK! ROLLBACK!")
return res.serverError(e);
}
// Commit the transaction
sails.models.user.query("COMMIT", function (err) {
if (err) {
throw new Error(err);
}
payout = {success: true};
console.log("PAYOUT PAYOUT", payout);
console.log("PAYOUT PAYOUT", transaction);
return res.json(payout);
});
});
});
} // END of if user.coins>0
});
});
}
// If there are any problems, roll back the transaction
catch (e) {
User.query("ROLLBACK", function (err) {
// The rollback failed--Catastrophic error!
if (err) {
return res.serverError(err);
}
// Return the error that resulted in the rollback
return res.serverError(e);
});
}
So when I run a loop(5times) in the frontend console, then it creates 5 records in the myTransaction table. How Can I do this properly?