0

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?

1
  • 1
    Put that in a separate Node.js module and require it in all the files? Commented Oct 24, 2014 at 16:49

1 Answer 1

6

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);
                }           
            });

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

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.