Last Updated: February 25, 2016
·
877
· robcolbert

RAII Pattern For API Controllers on Node.js

function HomeController (config, server) {
  this.config = config;
  this.server = server;

  server.get( // restify style route logic
    {
      'name': 'Home',
      'path': '/',
      'version': '0.0.1'
    },
    this.getHomePage.bind(this)
  );
}

HomeController.prototype.getHomePage = function (req, res, next) {
  res.json({'message': 'This is just a quick test'});
  next();
};

module.exports = exports = HomeController;

The controller's constructor accepts a configuration and server object (adapt to Express & Restify as needed), and uses them to wire up the controller's routes to handler methods defined on the controller class.