A
A
alex4answ2020-09-05 08:11:21
Node.js
alex4answ, 2020-09-05 08:11:21

Where is the correct place to place the POST validator?

Good afternoon, I use express-validator, I can not decide where it is better to place the validator.
I use this approach:

router

middleware is no longer built in.
const router  = express.Router();
const userController = require('./userController');

router.route('/')
  .get(userController.getAll)
  .post(userController.create);

controller:
exports.create = async (req, res, next) => {
  const validator = require('./validators/userCreate'); // Чтобы грузить только при создании
  await validator(req, res);

  try {
    const user = await userService.create(req.body);
    res.status(201).json(user);
  } catch(err) {
    res.status(422).json({ message: err.message });
  }
};

In order for the validator to be loaded only when created, I request it (require) in a specific controller action.
The validator itself
const { body, validationResult } = require('express-validator');
modules.exports = validate([ body('email').isEmail(), body('name').isString() ]);

const validate = (validators) => { // хранится в utils, тут для наглядности
  return async (req, res) => {
    await Promise.all(validators.map((validator) => validator.run(req)));

    const errors = validationResult();
    if (!errors.isEmpty) {
      res.status(422).send({ errors: errors.array() });
    } 
     // будь это полноценным middleware, тут было бы next()
  }
};


All doubts come down to the fact that my validator is kind of middleware, but I can’t place it in the chain , because validators are very voluminous and I want to load them only with the right action .

How successful is my solution, or how are things like this implemented?

Answer the question

In order to leave comments, you need to log in

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question