My Express API exposes a POST endpoint to create a user, and i need to validate data before inserting it into database, i have two methods in mind:
Method 1: Include the model’s validation in the controller and repeat it for every model:
// controllers/users.js
exports.createUser = async function (req, res) {
const { username, email, password } = req.body;
/* validation logic */
/* interact with db */
Method 2: Move the validation logic to dedicated middleware:
// middleware/validators.js
exports.validateArticle = function (req, res, next) {};
exports.validateComment = function (req, res, next) {};
exports.validateUser = function (req, res, next) {
const { username, email, password } = req.body;
/* validation logic */
if (!isValid) {
return res.statusCode(400);
}
next();
};
// routes/users.js
const { validateUser } = require('../middlewares/validators');
router.route('/').post(validateUser, createUser);
my concern with method 2 is that the logic for one endpoint method would be scattered among many files, but which one of these methods follow best practices ?