我有一种情况,我想根据请求负载调用多个快速中间件。
These middlewares are generated from the express validator checkSchema method.
因此,我编写了一个中间件,可以访问请求对象,并且可以从请求负载中读取属性,然后决定必须运行哪个架构。
一个实现会像这样。
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.
如果是中间件,我可以调用 schema1(req, res, next);
如果有人经历过这个,请建议我手动运行中间件数组的方法是什么。
最佳答案
我已经发布了express-validator v6.0.0 ,这应该有助于解决此类问题。
现在有一个 .run(req)
方法,它应该让你 do things with express-validator in an imperative way .
对于您的用例,您可以执行以下操作:
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)));
}
});
自 checkSchema
returns an array of validation chains ,代码将它们每个映射到各自的执行 promise 。
当所有的 promise 完成后,您的代码可以继续执行并执行您想做的任何事情。也许检查 validationResult
是否有错误、相应地渲染不同的页面等等——由您决定!
关于node.js - 如何手动调用多个express中间件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56689959/