6

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!

Community
  • 1
  • 1
Henrik Andersson
  • 45,354
  • 16
  • 98
  • 92

1 Answers1

11

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!

freakish
  • 54,167
  • 9
  • 132
  • 169
  • Thanks for the answer! :) My question was "How to produce a .get(), .post() syntax". I might have to alter the question. The reason why I would like to refrain from checking for get/post in the function itself is just because of preference in this project. Thanks for pointing me in the right direction! :) Also I have a handlers-file where I add a lot of handlers that map to functions by the same name I'm not sure if that was made clear. – Henrik Andersson Jul 11 '12 at 09:06
  • this might be a totally moronic question but the handlers property isnt instatiated, it's just undefined. – Henrik Andersson Jul 11 '12 at 10:02
  • @limelights I've defined it at the begining of **2)** section: `var app = module.exports = { handlers : [],`. – freakish Jul 11 '12 at 10:27
  • yeah, i know, but it still turns up as undefined when i run it and i cant for the love of god see why it does it. – Henrik Andersson Jul 11 '12 at 10:30
  • @limelights Hmm, maybe you should post the code you've written and we look at it?? Remember that `this` always refers to the **holder** of a function (`app` in my case). Also you may trying converting the code into classical `function()` style, instantiate it and export it. – freakish Jul 11 '12 at 10:33
  • I'll try to the export but otherwise im using your exact code for testing purposes. :) – Henrik Andersson Jul 11 '12 at 10:45
  • i got it to work! I did learn a lot as well! :) Thanks for the excellent answer! :) – Henrik Andersson Jul 11 '12 at 14:29