Last Updated: February 25, 2016
·
1.174K
· 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.

Have a fresh tip? Share with Coderwall community!

Post
Post a tip
Did you know?

JavaScript on a page runs with the privileges of that origin. One altered library, tag manager, or snippet can read inputs, change what people see, and call your APIs as the user.

Security insights from Cside