forked from kilobit/wt-node
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathrouter.js
More file actions
248 lines (198 loc) · 6.82 KB
/
router.js
File metadata and controls
248 lines (198 loc) · 6.82 KB
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
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
"use strict";
/* Copyright (C) 2011 Kilobit */
/* WT is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* WT is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
var url = require("url");
// var logger = require("./logger");
var qsparser = require('querystring');
var Router = function (options) {
var that = this;
options = options || {};
this.routes = options.routes || {};
this.prerunChain = [
parseGetParameters,
parsePostData,
parseCookies
];
this.default_handler = options.default_handler || NotFoundHandler;
this.error_handler = options.error_handler || ServerErrorHandler;
this.route = function(request,response){
var data = {};
// Parse the request uri
var uri = url.parse(request.url);
// Loop over the routes
for(var route in that.routes) {
// Check for a match.
var match = that.routes[route].re.exec(uri.pathname);
if(match) {
data.url = match;
// Get the method handler
var method = that.routes[route].handlers && that.routes[route].handlers[request.method.toUpperCase()];
if(method) {
// Pass control to the routed method.
if(that.prerunChain.length > 0) {
return that.runBefore(request, response, data, method);
} else {
return method(request, response, data);
}
}
// Try the default route handler
if(typeof(that.routes[route].default_handler) === 'function') {
that.routes[route].default_handler(request, response);
}
}
}
// Try the default handler
if(typeof(that.default_handler) === 'function') {
return that.default_handler(request, response);
}
// No match, no default handler.
that.error_handler(request,response);
}
}
Router.prototype.setDefaultRouteHandler = function(path, handler) {
// Get existing route entries or create new ones.
var route = (this.routes[path]) ? this.routes[path] : {};
// Set the default handler on the route.
route.default_handler = handler;
// Add the route to the routes.
this.routes[path] = route;
}
Router.prototype.setRoutes = function(routes) {
this.routes = routes;
}
Router.prototype.clearPrerunChain = function() {
this.prerunChain = [];
};
Router.prototype.addPreHandling = function(fn) {
this.prerunChain.push(fn);
}
Router.prototype.setDefaultHandler = function(fn) {
this.default_handler = fn;
};
Router.prototype.runBefore = function(request, response, data, routeHandler) {
var run_count = 0;
var that = this;
var next = function() {
// if ( incoming_data ) {
// data = incoming_data;
// }
if(that.prerunChain.length === run_count) {
return routeHandler(request, response, data);
}
var now = that.prerunChain[run_count];
run_count++;
// var now = router.prerunChain.shift();
if( typeof now != 'function' ) {
throw new Error(now.toString() + " is not a function!");
}
return now(request, response, data, next);
};
next();
};
Router.prototype.setHandler = function(method, path, handler) {
// Get existing route entries or create new ones.
var route = (this.routes[path]) ? this.routes[path] : {};
var handlers = (route.handlers) ? route.handlers : {};
// Pre Compile the regex
if(typeof(route.re === 'undefined')) {route.re = new RegExp(path);}
// Set the handler on the route
handlers[method.toUpperCase()] = handler;
route.handlers = handlers;
// Add the route to the routes.
this.routes[path] = route;
};
Router.prototype.get = function(path, handler) { return this.setHandler('GET', path, handler); };
Router.prototype.post = function(path, handler) { return this.setHandler('POST', path, handler); };
Router.prototype.put = function(path, handler) { return this.setHandler('PUT', path, handler); };
Router.prototype.delete = function(path, handler) { return this.setHandler('DELETE', path, handler); };
Router.prototype.options = function(path, handler) { return this.setHandler('OPTIONS', path, handler); };
Router.prototype.head = function(path, handler) { return this.setHandler('HEAD', path, handler); };
var NotFoundHandler = function(request, response) {
response.writeHead(404, {'Content-Type': 'text/html'});
response.write("<html>\n\t<head>\n\t<title>404 Not Found</title>\n\t</head>\n");
response.write("<body><h1>Not Found</h1><p>The resource you requested, " + request.url + ", was not found on this server.</p></body>");
response.write("</html>");
response.end();
}
var ServerErrorHandler = function(request, response) {
response.writeHead(500, {'Content-Type': 'text/html'});
response.write("<html>\n\t<head>\n\t<title>500 Internal Server Error</title>\n\t</head>\n");
response.write("<body><h1>Server Error</h1><p>The server has encountered an error processing this request.</p></body>");
response.write("</html>");
response.end();
};
var parseGetParameters = function(request, response, data, next) {
var params = {};
// add get params
request.url.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m, key, value) {
params[key] = value;
});
if(!data.get) {
data.get = {};
}
if(!request.wt) {
request.wt = {};
}
request.wt.query = params;
data.get = params;
return next();
};
var parsePostData = function(request, response, data, next) {
if (!data) {
data = {};
}
if (!request.wt) {
request.wt = {};
}
request.wt.data = {};
data.post = {};
if (request.method.toUpperCase() !== "POST") {
return next();
}
if( request.headers && request.headers['content-type'] && request.headers['content-type'].indexOf('application/x-www-form-urlencoded') == -1) {
return next();
}
var postData = "";
request.setEncoding("utf8");
request.on("data", function(data) {
postData += data;
});
request.on("end", function() {
// Pass control to the routed method.
if (postData.match(/<(.*)>(.*)<\/(.*)>/)) {
request.wt.data = postData;
data.post = postData;
return next();
// return routeMethod(request, response, postData);
}
var parsed_post_data = qsparser.parse(postData);
request.wt.data = parsed_post_data;
data.post = parsed_post_data;
return next();
});
};
var parseCookies = function(request, response, data, next) {
data.cookies = {};
if(!request.headers || !request.headers.cookie) {
return next();
}
var cookies_array = request.headers.cookie.split(";");
cookies_array.forEach(function( cookie ) {
var parts = cookie.split('=');
data.cookies[parts.shift().trim()] = decodeURI(parts.join('='));
});
return next();
};
module.exports = Router;