Reputation: 5081
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.
Upvotes: 0
Views: 392
Reputation: 326
You can directly call schemas(req.params.myParam)
inside the checkSchema
middleware since the middleware will have access to the request object.
Upvotes: 1
Reputation: 36
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();
};
};
Upvotes: 1