【发布时间】:2018-12-10 07:27:28
【问题描述】:
export function valUPM() {
return (req: Request, _res: Response, next: NextFunction) => {
req
.checkBody(
"paymentType",
`paymentType: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
if (req.body.paymentType === "USP") {
req
.checkBody(
"storeId",
`storeId: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
} else if (req.body.paymentType === "CC") {
if (req.body.register) {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustBeBoolean")}`
)
.isBoolean();
} else {
req
.checkBody(
"register",
`register: ${messages.getFromSession(req, "mustNotBeEmpty")}`
)
.notEmpty();
}
}
req.getValidationResult().then(errs => {
if (errs.isEmpty()) {
return next();
}
const error = new BFFError(
400,
"BadRequest",
1,
errs.array().map(error => {
return { [error.param]: error.msg };
})
);
return next(Error(JSON.stringify(error)));
});
};
}
改变 API 后如何在 express 验证器中实现这种类型的逻辑
在 if 循环中调用 req.checkBody 或所需的验证函数可以实现如上所示的技巧,但在 API 更改后如何实现 我尝试了将paymentTYPE检查为自定义验证器并实施检查并将消息扔到自定义验证器中的解决方法,但密钥发生了变化。
使用当前的 APi 正确的方法是什么,因为这对于所有想要从 3.0.0 更新到最新的 express-validator API 的人都很有用
【问题讨论】:
标签: javascript node.js express express-validator