Created
December 7, 2012 01:56
-
-
Save mattneary/4230104 to your computer and use it in GitHub Desktop.
Node.js App Router
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 app = require('route'); | |
app.get({ | |
path: /\/api\//, | |
cb: function(req, res) { | |
res.end(JSON.stringify({success: true})); | |
} | |
}, { | |
path: /\/home\//, | |
cb: function(req, res) { | |
res.end("Hello"); | |
} | |
}).post({ | |
path: /\/api\//, | |
cb: function(req, res) { | |
res.end(JSON.stringify({success: true})); | |
} | |
}).e404(function(req, res) { | |
res.end("FAIL"); | |
}); | |
http.createServer(app).listen(8080); |
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 http = require('http'); | |
module.exports = (function() { | |
var rules = { GET: [], POST: [] } | |
var _404 = function(req, res) { res.writeHead(404); res.end(); }; | |
var Router = function(req, res, m /*placeholder*/) { | |
((m = (rules[req.method]||[]).filter(function(rule) { | |
return rule.path.test(req.url); // filter for a match to the pattern | |
})).length ? m.pop().cb : _404)(req, res); // if none, 404 | |
}; | |
var _chainable = function(action) { return function(){action.apply({}, arguments); return Router;}; }; | |
[["get", _chainable([].push.bind(rules["GET"]))], | |
["post", _chainable([].push.bind(rules["POST"]))], | |
["e404", _chainable(function(cb) { _404 = cb; })]].map(function(a){Router[a[0]] = a[1];}); | |
return Router; | |
})(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment