Created
April 23, 2011 12:52
-
-
Save ThisIsMissEm/938580 to your computer and use it in GitHub Desktop.
Simplistic API router for Connect
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var connect = require('connect'), | |
fs = require('fs'), | |
path = require('path'); | |
function _rr(file) { | |
var modules = {}; | |
var files = fs.readdirSync(file); | |
files.map(function(_file) { | |
var filepath = path.join(file, _file); | |
var stats = fs.statSync(filepath); | |
if (stats.isDirectory()) { | |
modules[path.basename(_file)] = _rr(filepath); | |
} else { | |
modules[path.basename(_file, '.js')] = require(filepath); | |
} | |
}); | |
return modules; | |
} | |
function rr(directory) { | |
var root = path.join(__dirname, directory); | |
return _rr(root); | |
} | |
exports.router = function(mount_path, handler_dir) { | |
var mp_length = mount_path.length; | |
var controllers = rr(path.join('../', handler_dir)); | |
var cache = {}; | |
var extRe = /\.(.+)/; | |
return function(req, res, next) { | |
if (req.url.substr(0, mp_length) !== mount_path) return next(); | |
var rpath = req.url | |
.substr(mp_length) | |
.replace(extRe, ''); | |
if (rpath.length === 0) { | |
cache[rpath] = false; | |
} else if (cache[rpath] === undefined) { | |
var segment, | |
ss = rpath.split('/'), | |
current = controllers, | |
cont = true; | |
while (ss.length && (segment = ss.shift()) && cont) { | |
if (current[segment]) { | |
current = current[segment]; | |
} else { | |
current = false; | |
cont = false; | |
} | |
} | |
cache[rpath] = current; | |
} | |
if (cache[rpath] === false) { | |
return connect.utils.badRequest(res); | |
} else if (typeof cache[rpath] === 'function') { | |
cache[rpath](req, res); | |
} else { | |
cache[rpath].index(req, res); | |
} | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment