快递
我想用快递验证来验证一些投入,但我有不同的设置比一个的文件中。
林验证如果body.payload不为空
this.validator.document
public document = async (req: Request, res: Response, next: NextFunction) => {
check("payload").exists({ checkNull: true });
try {
validationResult(req).throw();
next();
} catch (err) {
res.status(422).json({ errors: err.mapped() });
}
}
this.controller.document
public document = async (req: Request, res: Response): Promise<any> => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
}
documentRoute
this.router.post("/:id/document",
this.jwtGuard,
this.validator.document,
this.controller.document);
IM意识到检查本身就是一种中间件,让我怎么处理这个问题我现有的验证函数内可能收到一些其他验证。
目前,这是不行的,即使寿有效载荷被设置为null。它应该捕获错误并返回一个422响应,但事实并非如此。
回答如下:在validator.document
:
public document = () => check("payload").exists({ checkNull: true });
在documentRoute
:
this.router.post("/:id/document",
this.jwtGuard,
this.validator.document(), // notice the parentheses
this.controller.document);
更新:如果你要处理的validator.document
的错误,你需要声明的路线时要调用check
中间件收到:
this.router.post("/:id/document",
this.jwtGuard,
check("payload").exists({ checkNull: true }),
this.validator.document,
this.controller.document);
而在validator.document
:
public document = async (req: Request, res: Response, next: NextFunction) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
}
更新2:如果您有多个检查操作,并且不希望臃肿路线的定义,我建议你使用schema validation。