4

I'm using MySQL on Nodejs. I'm using mysql pool to create the connection:

Var mysqk = require ('mysql');
Var pool = mysql.createPool ({my configs});

My question is: Where in the app will I use pool.end() as reported in the documentation?

For example: in my www file, I created a code to release other things as I have pointed in de code. Should I use pool.end() there?

var app     = require('../app');
var debug   = require('debug')('cancela:server');
var http    = require('http');
var port = normalizePort(process.env.PORT || '4000');
app.set('port', port);
var server = http.createServer(app);

// my app codes...
..
.
.

process.once('SIGTERM', end);
process.once('SIGINT', end);

function end() {

    server.close(function(err){

    if(err) throw err();

        // Should I end the Pool connection here?  <<<<<<===================================
        // pool.end(function (err) {
        //   // all connections in the pool have ended 
        // });

        console.log('Server endded!');        

        /* exit gracefully */
        process.exit();
    });
}
wBB
  • 821
  • 1
  • 18
  • 39

1 Answers1

3

Sometimes you want to manually release the connection pool for whatever reasons so you can use pool.end() before eventually recreating the pool.

Most of times you want to release it when your server is about to shutdown so you can do what you are thinking. Pay attention to the location of the function call process.exit(). It must be called after the connection release, otherwise the pool won't finish to release.

function end() {
    server.close(function (err) {
        if (err) throw err;
        console.log('Server endded!');

        pool.end(function (err) {
            if (err) throw err;

            process.exit();
        });
    });
}
Wing-On Yuen
  • 657
  • 5
  • 9
  • Thanks! I'll try it. – wBB Jul 26 '17 at 14:23
  • Sorry for the delay in answering, but I had to interrupt what I was doing and as soon as I get back to work I'll let you know. Thanks! – wBB Jul 28 '17 at 00:29
  • Hi! I'm back a little bit more at this project. I know that what you have suggested should works. However, I don't know how to bring the global connection object to where `server.close` is. I'm a beginner, and I'm still trying to understand how "Dependency Injection" works. So without "DI" I did several `require` for the project and I'm kind of lost. My project is with Nodejs and Express as well as beginner. – wBB Aug 01 '17 at 00:44
  • Yes without DI, you should use `require`. If you want to use DI, you may check [this projet](https://github.com/talyssonoc/node-api-boilerplate). – Wing-On Yuen Aug 02 '17 at 11:41