bodruk
bodruk

Reputation: 3262

Global objects with Node.js + Express

I'm studying Node.js + Express, coding a basic login example. My /login route is set inside the routes/login.js file:

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

var mysql = require('mysql');
var connectionpool = mysql.createPool({
    host     : 'localhost',
    user     : 'user',
    password : 'pass',
    database : 'database'
});

router.post('/', function(req,res){ 
    connectionpool.getConnection(function(err, connection) {
        if (err) {
            console.error('CONNECTION error: ',err);
            res.statusCode = 503;
              res.send({
                result: 'error',
                err:    err.code
            });
        } else {
            // Do something
        }
    });
});

module.exports = router;

I was wondering: how can I make the mysql or the connectionpool visible in the entire application? I don't want to redeclare them on each route file I'll create. I'm looking something like an include or require method.

Any idea?

Upvotes: 0

Views: 1270

Answers (1)

Evan Shortiss
Evan Shortiss

Reputation: 1658

Create a separate module to act as an interface to retrieving SQL connections like so:

    var mysql = require('mysql');
    var connectionpool = mysql.createPool({
      host     : 'localhost',
      user     : 'user',
      password : 'pass',
      database : 'database'
    });

    exports.getConnection = function (callback) {
      connectionpool.getConnection(callback);
    };

Then in another file:

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

        connections.getConnection(function (err, c) { 
    // Use c as a connection 
     c.query("select * from table limit 10 ",function(err,rows){
    //this is important release part 
                c.release();
                if(!err) {
                    console.log(rows);
                }           
            });

});

Upvotes: 6

Related Questions