forked from creationix/creationix
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathroute.js
27 lines (26 loc) · 906 Bytes
/
route.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
var Url = require("url");
module.exports = function setup(method, route, handler) {
var names = [];
var compiled = route.replace(/:[a-z$_][a-z0-9$_]*.?/gi, function (match) {
if ((/[^a-z$_0-9]$/i).test(match)) {
var end = match.substr(match.length - 1);
names.push(match.substr(1, match.length - 2));
return "([^" + end + "]+)" + end;
}
names.push(match.substr(1));
return "(.*)";
});
compiled = "^" + compiled + "$";
var regexp = new RegExp(compiled);
return function (req, res, next) {
if (req.method !== method) return next();
if (!req.hasOwnProperty("uri")) { req.uri = Url.parse(req.url); }
var match = req.uri.pathname.match(regexp);
if (!match) return next();
var params = {};
Array.prototype.slice.call(match, 1).forEach(function (value, i) {
params[names[i]] = value;
});
handler(req, res, params, next);
}
};