-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
96 lines (85 loc) · 2.47 KB
/
index.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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
var simplerouter = function () {
var URL = require('url');
var routes = [];
var defaultRoute;
var defaultError = {
statusCode: 501,
statusMessage: 'Not Implemented'
};
var that;
var requestListener = function (request, response) {
var parsedUrl = URL.parse(request.url);
if (!routes.some(function (route, ix) {
if (route.method !== undefined) {
if (typeof route.method === 'string' &&
request.method !== route.method) {
return false;
}
else if (typeof route.method === 'object' &&
route.method.indexOf(request.method) === -1) {
return false;
}
}
if (typeof route.url === 'string') {
route.url = new RegExp(route.url);
}
var matches = parsedUrl.path.match(route.url);
if (matches === null) {
return false;
}
else {
// route matched, handle request to response action:
if (matches.length > 1) {
route.action(request, response, matches);
}
else {
route.action(request, response);
}
return true; // stop processing of further route tests
}
})) { // no route found, ...
if (defaultRoute !== undefined) { // ... but we have a default one:
defaultRoute.action(request, response);
}
else {
// ... and we have no default one - return HTTP error:
response.writeHead(defaultError.statusCode, defaultError.statusMessage);
response.end();
}
}
// one route matches -> nothing to be done since response handling is done
// by corresponding route.action...
};
that = requestListener;
// PUBLIC METHODS:
var addRoutes = function (rs) {
var i;
if (typeof rs === 'object' && rs.constructor !== Array) {
// single route object:
routes.push(rs);
}
else { // [] of route objects:
for (i = 0; i < rs.length; i++) {
routes.push(rs[i]);
}
}
};
that.addRoutes = addRoutes;
that.addRoute = addRoutes; // for convenience
var setDefaultRoute = function (route) {
defaultRoute = route;
};
that.setDefaultRoute = setDefaultRoute;
var setDefaultError = function (error) {
defaultError = error;
};
that.setDefaultError = setDefaultError;
// init with optionally given routes:
if (arguments.length > 0) {
for (var i = 0; i < arguments.length; i++) {
addRoutes(arguments[i]);
}
}
return that;
};
module.exports = simplerouter;