gpt4 book ai didi

node.js - express-validator - 自定义错误输出

转载 作者:行者123 更新时间:2023-12-03 08:21:06 26 4
gpt4 key购买 nike

我正在使用快速验证器来验证 json 正文。

路由器

router.post('/login', [
body('mobno')
.exists().withMessage('Required')
.isLength({ min: 10, max: 12 }).withMessage('10-12 characters')
.isNumeric().withMessage('Numeric'),
body('password')
.not().isEmpty().withMessage('Password is required'),
], async (req, res, next) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.json({ errors: errors.array(), success: false, msg: 'Check Parameters' });
}
// do stuff and respond
});

回复
{
"errors": [
{
"value": "998716***658()",
"msg": "10-12 characters",
"param": "mobno",
"location": "body"
},
{
"value": "998716***658()",
"msg": "Numeric",
"param": "mobno",
"location": "body"
}
],
"success": false,
"msg": "Check Parameters"
}

在前端,我使用的是 Vuetify,因此我需要采用前端可以轻松使用的格式。

预期产出
{
"errors": {
"mobno": [
"10-12 characters",
"Numeric"
]
},
"success": false,
"msg": "Check Parameters"
}

问题
  • 是否有任何我可以 Hook 的选项/功能将格式化 errors以我想要的方式。
  • 我正在考虑使用 Lodash 进行这种转换,关于如何实现这一点的任何建议?
  • 最佳答案

    您可以使用 lodash 链按 param 对错误进行分组。 ,然后将每个组中的项目映射到 msg属性(property)。然后你可以结合errors对象与使用对象传播的先前结果。

    const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}

    const errors = _(data.errors)
    .groupBy('param')
    .mapValues(group => _.map(group, 'msg'))
    .value()

    const result = {
    ...data,
    errors
    }

    console.log(result)
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.14/lodash.js"></script>


    以及使用 lodash/fp 和 _.flow() 的管道方法:

    const { flow, groupBy, mapValues, map } = _

    const transform = flow(
    groupBy('param'),
    mapValues(map('msg'))
    )

    const data = {"errors":[{"value":"998716***658()","msg":"10-12 characters","param":"mobno","location":"body"},{"value":"998716***658()","msg":"Numeric","param":"mobno","location":"body"}],"success":false,"msg":"Check Parameters"}

    const result = {
    ...data,
    errors: transform(data.errors)
    }

    console.log(result)
    <script src='https://cdn.jsdelivr.net/g/lodash@4(lodash.min.js+lodash.fp.min.js)'></script>

    关于node.js - express-validator - 自定义错误输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57022179/

    26 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com