Background
I'm making a simple web server using express.js on top of node.js. When I'm making the route handlers for my server I inevitably have to factor out some common functionalities. So I want to make a baseHandler which has all the common handler functionalities like DB connection, and when I'm writing other route handlers I want to 'extend' the baseHandler to conveniently obtain those common handler capabilities.
What I am trying
What are the ways of achieving it, and what is the correct way to do so? I am trying a pretty straight forward solution, I wrote baseHandler as a normal handler module, having a local mysql instance and exports the functions which manipulates the database. Code below:
// Mysql
var _mysql = require('mysql');
// Mysql connection
exports.getDbHandle = function() {
var mysql = _mysql.createConnection({
host: xxx
port: xxx
user: xxx
password: xxx
database: xxx
});
return mysql;
};
Then in my route handlers I will simply require this module and use whatever functions it has. This seems to solve the problem, but I have a feeling that it is not the right way to do it. As I will have an instance of the baseHandler module in my route handler and it feels like a utility module, rather than a part of the route handler on its own.
Question
So what is the right way to extend modules in nodejs?
Put the common functionality into middleware that you can plug into the routes that need that functionality instead of creating a class hierarchy. That forces you to cleanly decouple the functionality into independent components. The middleware can make things like database connections available to the routes by adding them as properties of the req request object.