mindparse
mindparse

Reputation: 7215

Express - Separating route handler logic into controllers

I have seen examples of separating out Express router logic into controller files such as meanJS

E.g.

var express = require('express'),
  router = express.Router(),
  catalogues = require('../controllers/catalogues');

router.route('/catalogues')
  .get(catalogues.apiGET)
  .post(catalogues.apiPOST);

../controllers/catalogues

var request = require('request');

exports.apiGET = function(req, res) {
  var options = prepareCataloguesAPIHeaders(req);
  request(options, function(err, response, body){
    res.send(body);
  });
};

exports.apiPOST = function(req, res) {
  var options = prepareCataloguesAPIHeaders(req);
  options.json = true;
  options.body = stripBody(req.body);
  request(options, function(err, response, body){
    res.send(body);
  });
};

I have not seen any mention of this in the Express docs, so is this just a new way of thinking in terms of keeping the logic separate from the route definitions?

Are there any performance or other other gains achieved by using this approach?

Upvotes: 0

Views: 568

Answers (1)

pgrodrigues
pgrodrigues

Reputation: 2078

MEAN.js tries to follow the MVC pattern (Model-View-Controller) in the server side and the result is the logic division between mongoose models, server templates, and controllers.

As a way to improve code organization it is common to separate routes and controllers to their own files as well. In a huge app it helps developers to maintain the code.

Regarding performance, I don't believe there's any improvement.

Upvotes: 2

Related Questions