express-validator-自定义错误输出

时间:2019-07-13 19:25:30

标签: node.js error-handling lodash express-validator

我正在使用快速验证器来验证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. 是否有我可以挂钩的任何选项/功能,它们可以按照我想要的方式格式化errors
  2. 我正在考虑使用Lodash进行此转换,有关如何实现此目标的任何建议?

1 个答案:

答案 0 :(得分:1)

您可以使用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>