Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

URL routing in Node.js

Homework done:

The Node Beginner Book

How do I get started with Node.js [closed]

Structuring handlers in Node

Backstory: I wanted to try and write my own framework but I'm running into some troubles, most likely due to not understanding it fully.

What I want to achieve is a syntax that looks like this:

var app = require('./app'); //this part is understood and it works in my current code.
app.get('/someUrl', function(){ //do stuff here });
app.post('/someOtherUrl', function(){ //do stuff here });

I know of the Express-framework that has this same syntax but reading their source code still eludes me.

This might be a trivial task to achieve but I simply can't produce it, yet.

Trying to require('./app'); in a file deeper in the application produces a undefined object, so I'm guessing that a server is a singleton object.

So what have I tried?

My current code looks like this, and somehow I feel like this is the way to go, but I can't apparently do it like this.

I'm omitting all the require(); statements to keep it more readable.

server.js:

var app = module.exports = {
    preProcess: function onRequest(request, response){
        processor.preRequest(request); //this object adds methods on the request object
        var path = urllib.parse(request.url).pathname;
        router.route(urls, path, request, response);
    },
    createServer: function() {
        console.log("Server start up done.");
        return this.server = http.createServer(this.preProcess);
    }
};

exports.app = app;

At the time of writing I'm experimenting with extending this object with a get() method.

index.js:

var app = require('./server');
app.createServer().listen('1337');

the router.route() bit basically sends the request onward into the application and inside the router.js-file I do some magic and route the request onward to a function that maps (so far) to the /urlThatWasRequested

This is the behavior I'd like to leave behind. I know this might be a pretty tall order but all my code is easily discardable and I'm not afraid of rewriting the entire codebase as this is my own project.

I hope this is sufficient in explaining my question otherwise, please say what I should add to make this a bit more clear.

Thanks in advance!

like image 629
Henrik Andersson Avatar asked Jul 11 '12 08:07

Henrik Andersson


1 Answers

I'm not exactly sure what your question is, but here's some thoughts:

1) You are creating a circular reference here:

var app = module.exports = {
    // some other code
}
exports.app = app;

You add app as a property of app. There's no need for the last line.

2) You need to hold handlers in app. You can try something like this:

var app = module.exports = {
    handlers : [],
    route : function(url, fn) {
        this.handlers.push({ url: url, fn: fn });
    },
    preProcess: function onRequest(request, response){
        processor.preRequest(request);
        var path = urllib.parse(request.url).pathname;
        var l = this.handlers.length, handler;
        for (var i = 0; i < l; i++) {
            handler = this.handlers[i];
            if (handler.url == path)
                return handler.fn(request, response);
        }
        throw new Error('404 - route does not exist!');
    },
    // some other code
}

Note that you may alter this line: if (handler.url == path) in such a way that handler.url is a regular expression and you test path against it. Of course you may implement .get and .post variants, but from my experience it is easier to check whether a request is GET or POST inside the handler. Now you can use the code above like this:

app.route('/someUrl', function(req, res){ //do stuff here });

The other thing is that the code I've shown you only fires the first handler for a given URL it matches. You would probably want to make more complex routes involving many handlers (i.e. middlewares). The architecture would be a bit different in that case, for example:

preProcess: function onRequest(request, response){
    var self = this;
    processor.preRequest(request);
    var path = urllib.parse(request.url).pathname;
    var l = self.handlers.length,
        index = 0,
        handler;
    var call_handler = function() {
        var matched_handler;
        while (index < l) {
            handler = self.handlers[index];
            if (handler.url == path) {
                matched_handler = handler;
                break;
            }
            index++;
        }
        if (matched_handler)
             matched_handler.fn(request, response, function() {
                 // Use process.nextTick to make it a bit more scalable.
                 process.nextTick(call_handler);
             });
        else
             throw new Error('404: no route matching URL!');
     };
     call_handler();
},

Now inside your route you can use

app.route('/someUrl', function(req, res, next){ 
    //do stuff here
    next(); // <--- this will take you to the next handler
});

which will take you to another handler (or throw exception if there are no more handlers).

3) About these words:

Trying to require('./app'); in a file deeper in the application produces a undefined object, so I'm guessing that a server is a singleton object.

It isn't true. require always returns the reference to the module object. If you see undefined, then you've messed up something else (altered the module itself?).

Final note: I hope it helps a bit. Writing your own framework can be a difficult job, especially since there already are excelent frameworks like Express. Good luck though!

EDIT

Implementing .get and .set methods is actually not difficult. You just need to alter route function like this:

route : function(url, fn, type) {
    this.handlers.push({ url: url, fn: fn, type: type });
},
get : function(url, fn) {
    this.route(url, fn, 'GET');
},
post : function(url, fn) {
    this.route(url, fn, 'POST');
},

and then in routing algorithm you check whether type property is defined. If it is not then use that route (undefined type means: always route). Otherwise additionally check if a request's method matches type. And you're done!

like image 115
freakish Avatar answered Oct 23 '22 07:10

freakish