4
\$\begingroup\$

Which one of these two is better?

This one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect = function(){
           if(req.form.redirect) return url.parse(req.form.redirect);
           return {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }();
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }  
}

Or this one:

middleware.response_redirect = function(){
   return function (req, res, next){
       var redirect;
       if(req.form.redirect){
           redirect = url.parse(req.form.redirect);  
       }else{
           redirect = {
               protocol: "http",
               hostname: config.domain,
               pathname: "thanks",
           }
       }
       redirect.query = querystring.stringify({
           "status": "success",
           "message": req.form.message
       });
       return res.redirect(url.format(redirect);
   }  
}

The function within function thing bothers me a little. But so does setting redirect in two places.

\$\endgroup\$
8
\$\begingroup\$

How about a ternary operator?

var redirect = req.from.redirect
  ? url.parse(req.from.redirect)
  : {
    protocol: 'http',
    hostname: config.domain,
    pathname: 'thanks'
  };

Looks cleaner in my opinion.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.