Thursday 18 May 2017

Chain of asynchronous calls in a validation process in Node.js

This question is probably a bit of a self-indulgent code review request but I am not used to asynchronous programming and I'm in need of some validation before I continue further.

I am currently running a pretty simple web application in node.js that uses a series of middlewares in its signin process to validate the new resource.

Of particular interest is the controller method that serves as the last step of the process. If the request has passed every validation so far it still needs to go through this last one. It checks if a user with a similar email exists in the dabatase (the ORM in use is Sequelize), and then saves it to the database if that's the case.

Now I use bcrypt as a way to hash passwords before saving them, but this creates an additional layer of complexity to the process. Bcrypt runs asynchronously, and so do both orm methods called, which leads us to this block :

function(req, res) {
var = newuser = {
   email: req.body.email,
   password: req.body.password,
   display_name: req.body.display_name
};
bcrypt.hash(newuser.password, null, null, function (err, res) {
   if (err) {
      res.redirect('/auth/signup');
   }
   newuser.password = res;
   models.user.findOne({where: {email: newuser.email}}).then(user => {
      if (!user) {
         res.redirect('/auth/signup');
      }
      models.user.create(newuser).then(user => {
         if (!user) {
            res.redirect('auth/signup');
         }
         res.redirect('/auth/signin');
         }
      }
   }
}

My question is this : am I completely off base here and is there a more elegant way of executing the same general functions without 1) repeating the redirect for every fail case and 2) looking quite so ugly ?



via Nano

No comments:

Post a Comment