Answer the question
In order to leave comments, you need to log in
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:
const router = express.Router();
const userController = require('./userController');
router.route('/')
.get(userController.getAll)
.post(userController.create);
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 });
}
};
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()
}
};
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question