Skip to content
This repository

HTTPS clone URL

Subversion checkout URL

You can clone with HTTPS or Subversion.

Download ZIP
Browse code

Add controllers middleware

Change-Id: I5c7302ac93f2a0e628e20e901bbc1fa8e8dc9864
  • Loading branch information...
commit 1fe551c836266d9756c1dcaf9403eb295b60cfe3 1 parent db2113f
authored

Showing 1 changed file with 53 additions and 0 deletions. Show diff stats Hide diff stats

  1. 53  controllers.js
53  controllers.js
... ...
@@ -0,0 +1,53 @@
  1
+var Url = require('url'),
  2
+    Fs = require('fs'),
  3
+    Path = require('path');
  4
+
  5
+// MVC style controller routing
  6
+module.exports = function (root, controllerFolder) {
  7
+
  8
+  // Normalize mount points to always end in /
  9
+  if (root[root.length - 1] !== "/") { root += "/"; }
  10
+  // Normalize controller folder so require understands it
  11
+  controllerFolder = Fs.realpathSync(controllerFolder);
  12
+
  13
+  // Load the controllers at startup
  14
+  var controllers = {};
  15
+  Fs.readdirSync(controllerFolder).forEach(function (name) {
  16
+    var pos = name.lastIndexOf('.');
  17
+    var ext = name.substr(pos + 1);
  18
+    if (ext === 'js') {
  19
+      controllers[name.substr(0, pos)] = require(controllerFolder + "/" + name);
  20
+    }
  21
+  });
  22
+
  23
+  // Generate a request handling function  
  24
+  return function (req, res, next) {
  25
+    // parse out pathname if it's not there already (other middleware may have done it already)
  26
+    if (!req.hasOwnProperty('uri')) { req.uri = Url.parse(req.url); }
  27
+    
  28
+    // Mount relative to the given root
  29
+    var path = req.uri.pathname;
  30
+    if (path.substr(0, root.length) !== root) { return next(); }
  31
+    
  32
+    // Get the requested controller and method
  33
+    var parts = path.substr(root.length).split('/');
  34
+    if (parts.length === 0) { parts[0] = "index"; } // Default module to "index"
  35
+    if (parts.length === 1) { parts[1] = "index"; } // Default method to "index"
  36
+    
  37
+    // Find the controller
  38
+    var controller = parts.shift();
  39
+    if (!controllers.hasOwnProperty(controller)) { return next(); }
  40
+    controller = controllers[controller];
  41
+    
  42
+    // Find the method
  43
+    var method = parts.shift();
  44
+    if (!controller.hasOwnProperty(method)) { return next(); }
  45
+    
  46
+    // Call it!
  47
+    var args = [req, res, next];
  48
+    args.push.apply(args, parts);
  49
+    controller[method].apply(controller, args);
  50
+  };
  51
+  
  52
+};
  53
+

0 notes on commit 1fe551c

Please sign in to comment.
Something went wrong with that request. Please try again.