DEV Community

Margaret W.N
Margaret W.N

Posted on • Edited on

The C in MVC: Controllers

6 days ago, I thought I was done with the sales inventory API until i asked a friend to review my code and he was like, "🤔mmmmh... you need controllers". My immediate reaction was what are those? And why on earth do I need them? I did not ask though, lest I'd be hit with an article: shorthand for go figure it out yourself😅. A few days/articles/videos later, here are the answers to my questions.

What are controllers?

A controller is a component of MVC (model-view-controller) that processes the business logic of an application. MVC is a design or architectural pattern used to separate 'apllication concerns' that is: the data logic, business logic and UI logic. The M (model) handles the data logic while the V (view) handles the UI logic.

Why do we need controllers?

When using the MVC pattern the controller acts as the interface allowing communication between the model and view. You may wonder: Is it mandatory to use MVC? No. You may choose to use other design patterns such and MVVM (Model View View Model) or better still choose not to use any design pattern.

A basic implementation

Initially I had the logic in the routes files.

router.route('/users/login')
    .post((req, res) => {
      User.findOne({ email: req.body.email }, async (err, user) => {
        if (err) {
          return res.send(err);
        }
        if (await bcrypt.compare(req.body.password, user.password)) {
          return res.send(`Welcome back ${user.firstName}`)
        }
        return res.send('Wrong Password');
      })
    });
Enter fullscreen mode Exit fullscreen mode

I'll be moving all the logic to controller files and passing a function call.

User route.js file:

const express = require(`express`);
const userController = require('../controllers/userController');

const router = express.Router();

router.route('/users/login')
  .post(userController.userLogin);
Enter fullscreen mode Exit fullscreen mode

User controller.js File:

const User = require('../Models/userModel');
const bcrypt = require('bcrypt');

const userLogin = (req, res) => {
  User.findOne({ email: req.body.email }, async (err, user) => {
    if (err) {
      return res.send(err);
    }
    if (await bcrypt.compare(req.body.password, user.password)) {
      // return res.send('Login sucessful')
      return res.send(`Welcome back ${user.firstName}`)
    }
    return res.send('Wrong Password');
  })
}

module.exports = {
  userLogin
}
Enter fullscreen mode Exit fullscreen mode

It's that simple!

Day 27

Top comments (0)