繁体   English   中英

在 typecipt 中使用 joi 路径参数验证器发送自定义 json 响应

[英]send custom json response with joi path param validator in typescipt

我有使用 GET 方法的路由,它接受 url 路径中的 id 参数。 我正在使用正则表达式模式验证该 ID。 我可以使用以下代码成功验证。

const validate = require("express-joi-validate");
router.get("/finderrorlog/:id", validate(errorLogSchema),async (req: Request, res: Response) => {
  try {

      // Yes, it's a valid ObjectId, proceed with `findById` call.
      let result = await errlogsvc.GetErrroLogDetails(req.params.id);
      res.json({
        status: true,
        result: result,
      });


  } catch (e) {
    console.log(e);
    logger.error(e);
    res.json({ status: false, error: e });
  }
});

要验证的架构

export const errorLogSchema = {
    params: {
      id: Joi.string()
      .pattern(new RegExp('^[0-9a-fA-F]{24}$'))
    }
  }

但这里的问题是catch永远不会被执行。 我想要这样的回应

{
"status" : false,
"error: " id did not match te pattern"
}

但我得到错误

   {
        "message": "'params.id' with value '5b43c4qfk4e0f07c381392' fails to match the required pattern: /^[0-9a-fA-F]{24}$/",
        "field": "params.id"
    }

如何根据我的要求获得自定义响应?

我找到了不必使用validate(errorLogSchema)并且仍然可以验证数据的解决方案。

传递请求参数

const reqObject = findErrorLogRequestSchema.validate(req.params);

定义架构

export const findErrorLogRequestSchema = Joi.object({
    id: Joi.string()
    .pattern(new RegExp('^[0-9a-fA-F]{24}$')).message("Id is not valid")
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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