dorexx45
dorexx45

Reputation: 41

node-mysql pool and socket.io

I'm currently using a single mysql connection for all the users on my app. I would like to start using a pool (it should be more optimized, right?) but I have a "structural" problem: the createPool method only works with callback and I can't understand how to pass the connection to the socket.io event.

I mean, in the server.js file there is a point where the connection is build

pool.getConnection(function(err, connection) {
    //I'm supposed to use the connection here
}

and then there is a point where the socket events are "catched"

io.sockets.on('connection', function(socket){
    socket.on('userLogin', function(id_user){
        //I need the connection here to run a query with 'id_user'!
    });
});

In the second point I need the connection and then I can run

connection.query('SELECT bla bla bla...', function(err, data){
    connection.end();
});

I think this is the only way to have a different connection for every user connected to the app but I really can't understand how to "pass" the connection to the socket.io "space".

Upvotes: 1

Views: 1429

Answers (1)

robertklep
robertklep

Reputation: 203359

Ask the pool for a connection when you need it:

var pool = mysql.createPool(...);

io.sockets.on('connection', function(socket) {

  socket.on('userLogin', function(id_user) {
    pool.getConnection(function(err, connection) {
      // assuming err was null here...
      connection.query(..., function(err, data) {
        // return the connection to the pool as soon as possible
        connection.end();

        // process data
        ...
      });
    });
  });
});

Because of the pooling, pool.getConnection() is a pretty cheap call so there's not big impact when you call it on-demand.

Upvotes: 2

Related Questions