Kamal Kakkar
Kamal Kakkar

Reputation: 314

Where we put validation logic in nodeJs MVC?

i divided nodeJs app into MVC architecture Model Controller services Router tools logs my question is where i can put validation of rest api in service layer or controller layer. i am using express module and i want to use express-validater module for validation. which one is better approach ?

Upvotes: 6

Views: 4490

Answers (2)

dimitris tseggenes
dimitris tseggenes

Reputation: 3186

UPDATE 26/6/2020

You can add another folder (validation) in your architecture. This folder should contain validation middlewares

/validation/auth.js

exports.signup = [
    check('email').isEmail(),
    (req, res, next) => {
        const errors = validationResult(req);
        if (!errors.isEmpty()) {
            return res.status(422).json({ errors: errors.array() });
        }
        else next();
    }
];

// more middlewares 

Now inside your route file you can use the validation middleware you want right before the controller layer.

const express = require('express');
const { check } = require('express-validator/check');
const validate = require('../validation/auth');
const authController = require('../controllers/auth');

const router = express.Router();

router.post('/signup', validate.signup, authController.postSignup);

module.exports = router;
 

That way you enter the controller layer, only if validation is successfull.

Upvotes: 7

unflores
unflores

Reputation: 1810

I don't know about everyone, but I typically keep my http validation info in a directory with my controller. If this is your setup, I would put them in the items directory.

- controllers/
   - items/
     - index.js
     - validations.js

This is because the validations are pretty concretely linked with the items endpoints. I use other validations for inserting into a data store for instance.

Something like that should make them easier to find, and less annoying to require, since they are in the same directory.

Upvotes: 1

Related Questions