Search code examples
javascriptexpressexpress-validator

How to pass req.params as an an argument to a middleware function?


I'm trying to figure out a way to use req.params as an argument in my middleware. Take this (obviously broken) code for example:

router.post('/:myParam', checkSchema(schemas[req.params.myParam]), async (req, res, next) => {
  // do stuff
})

The goal here is that I am using express-validator and I load a dynamic schema based on what param is passed. The above code is obviously broken because I don't yet have the scope to access the req variable, I'm just trying to illustrate what I'm trying to accomplish.


Solution

  • if you know the possible params ahead, you could do something like the following:

    router.post("/:myParam", checkSchema("soccer"), async (req, res, next) => {});
    
    //checkSchema.JS
        const soccerSchema = require("../schemas/soccerSchema");
        const swimmingSchema = require("../schemas/swimmingSchema");
    
        module.exports = function (schemaName) {
          return (req, res, next) => {
            const schemas = { soccer: soccerSchema, swimming: swimmingSchema };
            //You can access it here schemas[schemaName]
            console.log(schemas[schemaName]);
            next();
          };
        };