【发布时间】:2017-12-03 05:58:51
【问题描述】:
在放下 NodeJS 几年后,我正在尝试重新学习它,因此我正在构建一个小型银行网站作为测试。我决定将 Sequelize 用于我的 ORM,但我在以我喜欢的方式在人与人之间汇款时遇到了一些麻烦。 这是我的第一次尝试:
// myUsername - who to take the money from
// sendUsername - who to send the money to
// money - amount of money to be sent from `myUsername`->`sendUsername`
// Transaction is created to keep a log of banking transactions for record-keeping.
module.exports = (myUsername, sendUsername, money, done) => {
// Create transaction so that errors will roll back
connection.transaction(t => {
return Promise.all([
User.increment('balance', {
by: money,
where: { username: myUsername },
transaction: t
}),
User.increment('balance', {
by: -money,
where: { username: sendUsername },
transaction: t
}),
Transaction.create({
fromUser: myUsername,
toUser: sendUsername,
value: money
}, { transaction: t })
]);
}).then(result => {
return done(null);
}).catch(err => {
return done(err);
});
};
这行得通,但它在增加模型时没有验证模型。当模型未验证时,我希望交易失败。我的下一个尝试是去回调,这里显示(相同的函数头):
connection.transaction(t => {
// Find the user to take money from
return User
.findOne({ where: { username: myUsername } }, { transaction: t }) .then(myUser => {
// Decrement money
return myUser
.decrement('balance', { by: money, transaction: t })
.then(myUser => {
// Reload model to validate data
return myUser.reload(myUser => {
// Validate modified model
return myUser.validate(() => {
// Find user to give money to
return User
.findOne({ where: { username: sendUsername } }, { transaction: t })
.then(sendUser => {
// Increment balance
return sendUser
.increment('balance', { by: money, transaction: t })
.then(sendUser => {
// Reload model
return sendUser.reload(sendUser => {
// Validate model
return sendUser.validate(() => {
// Create a transaction for record-keeping
return Transaction
.create({
fromUser: myUser.id,
toUser: sendUser.id,
value: money
}, { transaction: t });
});
});
});
});
});
});
});
});
}).then(result => {
return done(null);
}).catch(err => {
return done(err);
});
这行得通,因为钱仍然在人与人之间转移,但它仍然不能验证模型。我认为原因是.validate() 和.reload() 方法没有能力在其上添加transaction: t 参数。
我的问题是,是否有办法在事务中进行验证,但我也希望得到一些帮助来解决这个“回调地狱”。再说一次,我有一段时间没有做过 JS,所以我现在才知道可能有更好的方法来做这件事。
谢谢!
【问题讨论】:
标签: javascript node.js validation transactions sequelize.js