简体   繁体   中英

Choosing between 2 middleware in express

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.

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 scheme 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 this like:

app.use(middlewareStrategy);   // this sets req.schema to be used by later middleware

Then, you can use another middleware that expects to find the req.schema property to do its job:

app.use(customMiddleware);   // this middleware uses req.schema

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM