在打字稿中使用 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")
});
我有使用 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")
});