Hello i am creating a validation middleware but the problem is i have 2 types to the same endpoint so i created two schema for each.
All i want to do is when type is somthing pass through middleware_a esle return middleware_b
here is my idea but its not working
const middlewareStrategy = (req,res,next) => {
if(req.params.type === "Something"){
return custom_middleware(schemas.A_body);
}
return custom_middleware(schemas.B_body);};
A_Body here is just validation schema.
CodePudding user response:
It's a bit hard to tell eactly what you're trying to do because you don't show the actual middleware code, but you can dynamically select a middleware a couple of different ways.
Dynamically call the desired processing function
const middlewareStrategy = (req,res,next) => {
const schema = req.params.type === "Something" ? schemas.A_body : schemas.B_body;
bodyStrategy(schema, req, res, next);
};
In this middleware, you're dynamically calling a bodyStrategy function that takes the schema and res, res, next so it can act as middleware, but will know the schema.
Create a middleware that sets the schema on the req
object
const middlewareStrategy = (req,res,next) => {
req.schema = req.params.type === "Something" ? schemas.A_body : schemas.B_body;
next();
};
Then, use it like this:
// this sets req.schema to be used by later middleware
app.use(middlewareStrategy);
Then, you can use another middleware that expects to find the req.schema
property to do its job:
// this middleware uses req.schema
app.use(customMiddleware);
If this isn't exactly what you were looking for, then please include the code of your actual middleware so we can see what we're really aiming for.