Skip to content

Instantly share code, notes, and snippets.

@rook2pawn
Last active August 29, 2015 14:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rook2pawn/55662dff09fb539c9c05 to your computer and use it in GitHub Desktop.
Save rook2pawn/55662dff09fb539c9c05 to your computer and use it in GitHub Desktop.
Simple Chain Router
var methods = require('methods')
var routes = {}
var setter = function(method) {
return function() {
var args = [].concat.apply({},arguments).slice(1);
routes[method.toUpperCase()][args[0]] = args.slice(1);
}
}
var next = function() {
routes[this.req.method][this.req.url][++this.index](this.req,this.res,next.bind({req:this.req,res:this.res,index:this.index}));
}
var handle = function(req,res) {
if (routes[req.method][req.url])
routes[req.method][req.url][0](req,res,next.bind({req:req,res:res,index:0}));
}
methods.forEach(function(method) {
routes[method.toUpperCase()] = {}
handle[method] = setter(method)
})
module.exports = exports = handle
@rook2pawn
Copy link
Author

To use this here's an example of it

var http = require('http');
var router = require('./router');
var server = http.createServer(router)
server.listen(5050);

var a = function(req,res,next) {
    console.log(" function a")
    next()
}
var b = function(req,res,next) {
    console.log(" function b")
    next()
}
var c = function(req,res,next) {
    console.log(" function c")
    res.end("the article!\n");
}
router.get('/article',a,b,c);
router.post('/form',d,e);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment