在单独的文件中简化 Express-Validator 中间件的任何方法

any ways to simplify Express-Validator middleware in seperate file

我有一个项目需要使用 Express-Validator 进行大量验证,所以每次我需要验证某些东西时,我都喜欢在每个文件中这样做:

//Validation and Sanitizing Rules
const validationRules = [
  param('tab').isString().isLength({ min: 1, max: 8 }).trim().escape(),
  param('categoryID').isNumeric().trim().escape()
]
//Validate and get the result
const validate = (req, res, next) => {
  const errors = validationResult(req)
  // if every thing is good .. next()
  if (errors.isEmpty()) {
    return next()
  }
  //if something is wrong .. push error msg
  const extractedErrors = []
  errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }))
  return res.status(403).json({
    'status': 'alert error',
    'err': extractedErrors,
    msg: 'Any Error Msg Here:('
  })

我尝试创建文件 validator.js 然后在需要时调用它,但我不喜欢这个主意。

所以我正在考虑像 custom wrapper 这样的解决方案来简化我将来的验证..所以我尝试使用字母关键字来创建我的(自定义包装):

isString: 's',
isNumeric: 'n',
isLength: 'l',
trim: 'tr',
escape: 'es',
..etc

现在当我想验证类似 'number' 的东西时,我将它传递给对象中的自定义包装器:

customValidationRules({field : "categoryID", type: ['n','tr','es']})

包装器中的验证将是:

param('categoryID').isNumeric().trim().escape()

任何创建这种包装器的建议或指南.. ty

你应该翻转它,并使用如下结构:

const validators = {
    s: isString,
    n: isNumeric,
    ...
};

然后给定一个规则数组validationRules,如`['n'、'tr'、'es'],你可以这样做:

validationRules.reduce((rule, acc) => validators[rule].call(acc), param(paramName));