Search code examples
node.jsexpressroutesmiddlewareexpress-router

How to work with implied function parameters in NodeJS


In my website's routes file, I have a function like this:

router.post('/', ctrl1.validate, ctrl2.doSomething)

With the validate function looking like this:

function(req,res,next){
   var errors = validator.checkForm('myForm')
   if(errors){
      res.redirect("/")
   }else{
      next()
   }
}

If I want to pass parameters into the validator function (like the name of forms I want to validate) besides the implied req,res,next, how is that done? I have tried ctrl1.validate(formName) and ctrl1.validate(formName, req,res,next) with function(formName, req,res,next) in the controller, and neither work.


Solution

  • The ideal solution would be to identify what form you're working on from the data passed with the request in the first place. You don't show what that is, so we don't know exactly what to recommend or if that is feasible in this case.

    If you can't do that and want to have a generic function that you can use as a request handler in multiple places and you want to pass a parameter to it that is different in each of the different places you use it, then you need to create a function that returns a function.

    router.post('/', ctrl1.validate("someFormName"), ctrl2.doSomething)
    
    // definition of ctrl1.validate
    validate: function(formName) {
       // return a request handler that will knkow which formName to use
       return function(req,res,next){
           var errors = validator.checkForm(formName)
           if(errors){
              res.redirect("/")
           } else {
              next()
           }
        }
    }
    

    When you first call this method, it returns another function that is your actual request handler. That inside function then has access to both req, res, next from the request and has access to the formName that was originally passed in.