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

时间:2015-08-09 19:41:34

标签: javascript node.js mongodb asynchronous mongoose

我是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('/')
              })
            });
          });
        }             
      })
    }   
  })             
});

1 个答案:

答案 0 :(得分:1)

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

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模块。