重构Express验证器

时间:2019-07-07 11:06:24

标签: node.js express refactoring express-validator

我目前正在尝试在我的项目中实现express-validator。一切都正常,但是我的问题是有一块代码不断重复,因此我试图对其进行重构。

auth.validator.js

const { check, validationResult } = require('express-validator');
const User = require('./user.model');
const responseHelper = require('../../../helpers/response.helper');

const login = [
  check('email')
    .not().isEmpty().withMessage('Email is required.')
    .isEmail().withMessage('Email is not valid.')
    .normalizeEmail(),

  check('password')
    .not().isEmpty().withMessage('Password is required.')
    .isLength({ min: 6 }).withMessage('Password needs to be at least 6 characters.'),

  // this block of code will keep repeating
  function (req, res, next) {
    const errors = validationResult(req);
    if (errors) {
      return responseHelper.withValidationError(res, 422, errors);
    }
    next();
  },
];

// some other functions
// .......

exports.validate = (method) => {
  switch (method) {
    case 'login':
      return login;

    case 'register':
      return register;

    default:
      break;
  }
};

auth.route.js

const express = require('express');
const router = express.Router();
const v = require('./auth.validator');
const AuthController = require('./auth.controller');

router.post('/login', v.validate('login'), AuthController.login);

module.exports = router;

因此,我登录即将结束时的代码一直在重复。那么我将如何重构它,以使我不必每次都声明它?

0 个答案:

没有答案