Skip to content
Browse files

Refactoring, added method and path config to :before

  • Loading branch information...
1 parent a83753f commit 340d02a385db3a550e6ce87399abd2c9da4edba4 @Poincare committed Dec 25, 2011
Showing with 34 additions and 14 deletions.
  1. +27 −10 lib/Birbal.js
  2. +7 −4 lib/example.js
View
37 lib/Birbal.js
@@ -17,9 +17,7 @@ var Birbal = function (port, routes) {
}
}
- this.onRequest = function (request, response, specials) {
- var pathname = url.parse(request.url).pathname;
-
+ this.requestVars = function(request) {
var request_vars;
if(request.method == 'POST') {
@@ -39,13 +37,36 @@ var Birbal = function (port, routes) {
request_vars = query;
}
+
+ return request_vars;
+ };
+
+ this.callBeforeSpecial = function(pathname, method) {
+ if(this.specials["beforeFunc"] != null) {
+ this.specials["beforeFunc"](pathname, method);
+ }
+ };
+
+ this.callCatchAllSpecial = function(response, request_vars) {
+ response.writeHead(200, {"Content-Type":"text/html"});
+ response.write(this.specials["catchAllFunc"](request_vars));
+ response.end();
+ };
+
+ this.onRequest = function (request, response, specials) {
+ var pathname = url.parse(request.url).pathname;
+
+ var request_vars = this.requestVars(request);
var matched = false;
for(var i in routes) {
if(pathname === i) {
if(routes[i][1] === request.method) {
+ //since a route matched, we call the :before special if its registered
+ this.callBeforeSpecial(pathname, request.method);
+
response.writeHead(200, {"Content-Type":"text/html"});
response.write(routes[i][0](request_vars));
@@ -59,15 +80,11 @@ var Birbal = function (port, routes) {
}
if(matched != true) {
- if(this.specials["beforeFunc"] != null) {
- this.specials["beforeFunc"]();
- }
+ //none of the requests matched, call :catchall if registered
if(this.specials["catchAllFunc"] != null && this.specials["catchAllFunc"] != undefined) {
- response.writeHead(200, {"Content-Type":"text/html"});
- response.write(this.specials["catchAllFunc"](request_vars));
- response.end();
- }
+ this.callCatchAllSpecial(response, request_vars);
+ }
}
}
View
11 lib/example.js
@@ -1,4 +1,4 @@
-var serv = require("./Birbal.js");
+var akbar = require("./Birbal.js");
//called for "/" and "/else" for GET requests
function hello() {
@@ -11,15 +11,16 @@ function misc() {
}
//called before ever single request
-function before() {
- console.log("Hey! A request came in!");
+function before(pathname, method) {
+ console.log("Request on " + pathname + " with method " + method);
}
//called when no other request matches
function oops() {
return "Oops!";
}
+//routes, uses some specials, like :before, which is called before every req.
var routes = {
":before":[before],
"/":[hello, "GET"],
@@ -28,4 +29,6 @@ var routes = {
":catchall":[oops, "GET"]
};
-serv.Birbal(routes);
+PORT = 8888;
+
+akbar.Birbal(PORT, routes);

0 comments on commit 340d02a

Please sign in to comment.
Something went wrong with that request. Please try again.