So I am a systems programmer currently teaching myself web application programming. As is always the case when learning something new, I don't yet have a firm grasp on idiomatic implementations, or simply put, how to do something the "right" way.
After taking some time building a few games and trivial UI's using nothing but HTML and javascript, I am now venturing out into a non-trivial dynamic application. I am using Node as my server and have a question concerning how to route response handlers.
I am following a (seemingly) nice guide found here. This is the only guide I have found so far that takes you through how to build an actual application (as opposed to something like response.write("Hello world"); response.end();
).
The author proposes adding response handlers like so:
var server = require("./server");
var router = require("./router");
var requestHandlers = require("./requestHandlers");
var handle = {}
handle["/"] = requestHandlers.start;
handle["/start"] = requestHandlers.start;
handle["/upload"] = requestHandlers.upload;
server.start(router.route, handle);
The code should be self-explanatory, but essentially he is using an object as an associative container to map the resource requested in a query string to a handler. That's all well and good, but I would like to avoid adding a line to this file every time I add a new handler.
My idea was this; create a module for each handler and use some common interface to handle the response. Something like:
function handleReq(...) {
...
}
exports.handleRequest = handleReq;
I could then just require
the module dynamically, i.e.,
// in my router module
function route(pathName, args) {
// where 'pathName' is something obtained
// in a manner like so in the request handler:
// url.parse(request.url).pathname;
var handler = require(pathName);
handler.handleRequest(args);
}
Is there some flaw I am not seeing in this approach? It seems as though it would cut down on redundant code, but being a beginner in this field/technology I am suspicious. Perhaps the author just wanted to keep it simple, or as I guess may be the case, I am missing something.
Cheers and thanks in advance. Don't feel free to throw other seemingly unrelated advice at me as well should you see a reason to do so.