express-validator - 自定义错误输出

express-validator - Customize errors output

我正在使用快速验证器来验证 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"
}

问题

  1. 有没有我可以挂接的 option/function,它将按照我想要的方式格式化 errors
  2. 我正在考虑使用 Lodash 进行这种转换,关于如何实现这一点有什么建议吗?

您可以使用 lodash 链按 param 对错误进行分组,然后将每个组中的项目映射到 msg 属性。然后,您可以使用对象传播将 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>