Reputation: 361
I have a situation where I want to invoke multiple express middlewares depends on the request payload.
These middlewares are generated from the express validator checkSchema method.
So I have written a middleware which gets access to the request object and I can read a property from the request payload then take a decision on which schema has to be run.
An implementation would like this.
let app = express();
let schema1 = checkSchema({
field1: {
in: ["body"],
exists: {
errorMessage: "field1 is missing",
}
}
});
let schema2 = checkSchema({
field2: {
in: ["body"],
exists: {
errorMessage: "field 2 is missing",
}
}
});
app.post("/resource", (req, res, next) => {
if(req.body.type === "TYPE1") {
// Invoke schema1 middleware
}
if(req.body.type === "TYPE2") {
// Invoke schema2 middleware
}
});
Here schema1 and schema 2 are not single middleware. It is a middleware array.
If it was middleware, I could call schema1(req, res, next);
If anybody has gone through this, Please suggest me what is the approach to run a middleware array manually.
Upvotes: 2
Views: 914
Reputation: 41440
I have released express-validator v6.0.0, which should help addressing this kind of thing.
Now there is a .run(req)
method, which should let you do things with express-validator in an imperative way.
For your use case, you could do the following:
app.post("/resource", async (req, res, next) => {
if(req.body.type === "TYPE1") {
await Promise.all(schema1.map(chain => chain.run(req)));
}
if(req.body.type === "TYPE2") {
await Promise.all(schema2.map(chain => chain.run(req)));
}
});
Since checkSchema
returns an array of validation chains, the code is mapping each of them to their respective execution promise.
When all of the promises are finished, your code can continue executing and do whatever you want. Maybe check if there are errors with validationResult
, render a different page accordingly, etc -- up to you!
Upvotes: 4
Reputation: 12542
According to this question Use an array of middlewares at express.js there is one repo: https://github.com/blakeembrey/compose-middleware:
According to the readme:
app.use(compose([
function (req, res, next) {},
function (err, req, res, next) {},
function (req, res, next) {}
]))
So, what you can do is:
app.post("/resource", (req, res, next) => {
if(req.body.type === "TYPE1") {
compose(schema1)(req,res,next);
}
if(req.body.type === "TYPE2") {
compose(schema2)(req,res,next);
}
});
Upvotes: 0