gpt4 book ai didi

javascript - 表单验证和 Node JS - 避免厄运金字塔

转载 作者:行者123 更新时间:2023-12-03 09:18:21 25 4
gpt4 key购买 nike

我是 Node 新手,正在尝试进行一些用户注册表单验证。如果可能的话,我想重构以下代码以摆脱金字塔。我在 userService 模块中使用 Express Validator 来检查空字段和电子邮件验证,但 isValueUnique 函数只是 Mongoose findOne 查询。我正在使用 Graphics Magick 来调整图像大小。欢迎任何建议:

router.post('/register', function(req, res, next){
userCheck = userService.checkRegistration(req)
if(userCheck.errors){
return res.render('user/register', {
errors: userCheck.errors,
message: req.flash('error'),
title: 'People Power | Register'
})
}
User.isValueUnique({username: req.body.username}, function(err, user){
if(user){
return res.render('user/register', { message: 'Username already taken. Please choose another.', title: 'People Power | Register' });
}else{
User.isValueUnique({ email: req.body.email }, function(err, user){
if(user){
return res.render('user/register', { message: 'Email already registered. Please try again.', title: 'People Power | Register' });
} else{
User.createUser(userCheck, function(err, user){
if(err) throw err;
userService.resizeImage(userCheck, function(){
req.login(user, function(err){
req.flash('success', 'You have registered successfully, and are now logged in!')
res.redirect('/')
})
});
});
}
})
}
})
});

最佳答案

您可以使用async#waterfall改善“回调 hell ”,因此您的代码可能如下所示:

async.waterfall([

function (callback) {
User.isValueUnique({username: req.body.username}, callback);
},

function (user, callback) {
if (user) {
return res.render('user/register', { message: 'Username already taken. Please choose another.', title: 'People Power | Register' });
}
User.isValueUnique({ email: req.body.email}, callback);
}

function (user, callback) {
if (user) {
return res.render('user/register', { message: 'Email already registered. Please try again.', title: 'People Power | Register'};
}
User.createUser(userCheck, callback);
},

function (user, callback) {
userService.resizeImage(userCheck, callback);
},

function (callback) {
req.login(user, function(err) {
req.flash('success', 'You have registered successfully, and are now logged in!')
res.redirect('/')
});
}
], function (err) {
if (err) throw err;
});

我还建议查看PassportJS模块已经具有用于实现用户注册功能的模式套件。

关于javascript - 表单验证和 Node JS - 避免厄运金字塔,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31908145/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com