我目前参与了一个使用Geddy js框架的项目,这是我第一次使用这个框架。我目前正在尝试为用户修复模型中的create方法。代码如下:
this.create = function (req, resp, params) {
var self = this
, user = geddy.model.User.create(params);
//need to ensure that the user agrees with the terms and conditions.
// Non-blocking uniqueness checks are hard
geddy.model.User.first({username: user.username}, function(err, data) {
if (data) {
params.errors = {
username: 'This username is already in use.'
};
//self.transfer('add');
}
else {
if (user.isValid()) {
user.password = cryptPass(user.password);
user.suburb = "";
user.state = "";
user.postcode = "";
}
user.save(function(err, data) {
if (err) {
params.errors = err;
self.transfer('add');
}
else {
// setup e-mail data with unicode symbols
var mailOptions = {
from: "App ✔ <hello@app.com>", // sender address
to: user.email, // list of receivers
subject: user.username + " Thank you for Signing Up ✔", // Subject line
text: "Please log in and start shopping! ✔", // plaintext body
html: "<b>Please log in and start shopping!✔</b>" // html body
}
smtpTransport.sendMail(mailOptions, function(error, response){
if(error){
console.log(error);
}else{
console.log("Message sent: " + response.message);
}
// if you don't want to use this transport object anymore, uncomment following line
smtpTransport.close(); // shut down the connection pool, no more messages
});
self.redirect({controller: self.name});
}
});
}
});
};如果您查看代码,显然会检查所谓的用户是否有效,如下所示:if (user.isValid()) { user.password = cryptPass(user.password); user.suburb = ""; user.state = ""; user.postcode = ""; }
无论用户是否有效,都会继续进行“保存”。我在想为什么代码是这样的?这听起来很荒唐。我询问了项目中的原始开发人员,他说这个模型显然是他在创建项目时生成的。
有没有人能告诉我为什么save方法一开始就在if语句之外?这是Geddy的原始创建者想要的吗?或者真的很荒谬,我应该改变它?
谢谢。
发布于 2014-03-12 23:22:12
如果数据无效,Geddy的save()调用将会出错(除非设置了force标志,但实际上并没有设置)。它实际上使用相同的isValid()调用。所以,看起来这里只有一个人的方法来处理所有错误情况的单个错误处理器。
对于仅在数据看起来有效的情况下才使用加密数据设置的user.password,我猜这只是为了让“必须设置”类型的验证生效。有可能即使密码为空,加密的字符串也会被视为set。
https://stackoverflow.com/questions/22087295
复制相似问题