Update 2
Sails 1.0 now has full support for transactions through .getDatastore(). Example:
// Get a reference to the default datastore, and start a transaction.
await sails.getDatastore().transaction(async (db, proceed)=> {
// Now that we have a connection instance in `db`, pass it to Waterline
// methods using `.usingConnection()` to make them part of the transaction:
await BankAccount.update({ balance: 5000 }).usingConnection(db);
// If an error is thrown, the transaction will be rolled back.
// Or, you can catch errors yourself and call `proceed(err)`.
// To commit the transaction, call `proceed()`
return proceed();
// You can also return a result with `proceed(null, result)`.
});
Update
, , . , , , , , (.query(), .findOne() ..) . Waterline , , , (, pg mysql).
, transaction. ( ), , (, Postgres MySQL), .query() . :
buyItem: function(req, res) {
try {
User.query("BEGIN", function(err) {
if (err) {throw new Error(err);}
User.findOne(req.param("userId").exec(function(err, user) {
if (err) {throw new Error(err);}
user.balance = user.balance - req.param("itemCost");
user.save(function(err) {
if (err) {throw new Error(err);}
User.query("COMMIT", function(err) {
if (err) {throw new Error(err);}
res.json(user);
});
});
});
});
}
catch(e) {
User.query("ROLLBACK", function(err) {
if (err) {return res.serverError(err);}
return res.serverError(e);
});
}
}