10

I have the following in my app.js file:

var mysql = require('mysql');
var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'user',
    password: 'password',
    database: 'mydatabase'
});
connection.connect();

In routes/index.js, I currently have only the boilerplate code:

var express = require('express');
var router = express.Router();

module.exports = router;

How do I make available the connection object from the app.js file in routes/index.js?

1

4 Answers 4

15

I ended up splitting the database connection logic from the app.js file. In a separate file called connection.js, I have the following:

var mysql = require('mysql');

var connection = mysql.createConnection({
    host: 'localhost',
    port: 3306,
    user: 'user',
    password: 'password',
    database: 'mydatabase'
});

module.exports = connection;

Then in my route file, I add

var connection = require('../connection');

to the top of the file where all my other modules are brought in. In my instance, the connection.js file is one level higher than my route file, hence the ../ in the require() function parameter.

Sign up to request clarification or add additional context in comments.

3 Comments

That would be the other usual way. I like passing them in so I can easily mock them for testing.
@RobertMoskal 's answer (stackoverflow.com/a/25125755/1489912) is better, because you can use it for connection pooling. This one will eventually leave you with no control over the connections created.
@LloydBanks in this example, is a new DB connection being instantiated in every file that has var connection = require('../connection');? So, does that mean, if we separate our routes into different files, we should close the connection after the route handlers are done using the connection?
11

My preference is to do some simple dependency injection and pass the required resource into the router by wrapping the module in a function:

var express = require('express');

module.exports = function (connection) {
    var router = express.Router();
    //do stuff with the connection
    return router;

}

Then you just instantiate the router module in app.js as a function with the database connection as an argument:

app.use('/where/ever', require('./module-b')(connection)); 

Usually I wrap up the dependencies in an object:

app.use('/where/ever', require('./module-b')({db:connection})); 

This way you don't have to keep changing the function signature as dependencies are added. This gives you a super-lightweight inversion of control container for your express applications.

2 Comments

How is the object being passed here?
As long as you wrap each module in a function, it's just a repetition of the same pattern.
0

I had the same problem, and Lloyds' suggestion was kind of a solution for me but I just didn't want to be stuck on a single type of db, I want to be able to move my app to another db with just a new implementation of a single class. So that worked for me:

function DataAccess(connectionData) {
    //Using the connectionData...
}

var _dataAccessInstance;

module.exports = function (connectionData) {
    if (!_dataAccessInstance) {
        _dataAccessInstance = new DataAccess(connectionData)
    }
    return _dataAccessInstance;
};

And then the usage will be just require the file:

//The object is the connection data to be sent to the module
var dataAccess = require('./data-access')({});

Sure, this has its own flaws like every module must know and send the connection data. But I assume the data is stored in the configuration and all hte modules can access it.

Comments

0

Check out express-myconnection, it lets you access the MySQL connection from within your routes.

Update: After using express-myconnection in production, I would not recommend it - it leaks connections, causing requests to hang (callback will never be called), and it is no longer actively maintained.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.