如何制作用于检查空值的单个函数

How to make a single function for checking empty values

有一个路由器,我想在其中检查空值的字段,但这在其他路由器中也很有用,我怎样才能制作一个函数来检查正确的字段?

这是它的工作原理:https://tppr.me/b8sSO, https://tppr.me/xm0mY

我想要这样的东西:https://tppr.me/FQ9IE, https://tppr.me/C6P2Y

写一个中间件来检查验证结果。

validation.js

const { validationResult } = require('express-validator');
const rules = require('./rules');

const validate = (request, response, next) => {
  const errors = validationResult(request);
  if (errors.isEmpty()) {
    return next();
  }
  const extractedErrors = [];
  errors.array().map(err => extractedErrors.push({ [err.param]: err.msg }));

  return response.status(422).json({
    errors: extractedErrors,
  });
}

module.exports = {
  validate: validate,
  Rule: rules
};

和一个包含所有规则的文件 rules.js

const { body } = require('express-validator')

function registerRule() {
  return [

    // username must be an email
    body('username')
      .not().isEmpty()
      .isEmail(),
      // .isLength({ min: 5 })
      // .withMessage('Username must have more than 5 characters'),

    // password must be at least 5 chars long
    body('password', 'Your password must be at least 5 characters')
      .not().isEmpty()
      .isLength({ min: 5 }),
  ];
};

module.exports = {
  Register: registerRule.call()
};

并像这样使用它:

const validation = require('./libs/validation');

validate = validation.validate;
ValidationRule = validation.Rule;

router.post('/register', ValidationRule.Register, validate, (req, res, next) => {});

我用this来源来回答。