Skip to content

Instantly share code, notes, and snippets.

@Potentii
Created March 14, 2017 00:02
Show Gist options
  • Select an option

  • Save Potentii/ab5e97d14793693adf27ecc6ce0eff4f to your computer and use it in GitHub Desktop.

Select an option

Save Potentii/ab5e97d14793693adf27ecc6ce0eff4f to your computer and use it in GitHub Desktop.
Starting and stopping knex pool
/**
* The knex instance
*/
let knex = null;
/**
* Starts a knex instance and test its connections pool
* @return {Promise<knex>} A promise that resolves with the knex instance, or rejects if some error happened
*/
function start(){
// *Returning a promise chain:
return new Promise((resolve, reject) => {
// *Trying to get a knex instance:
try{
// *Requiring the knex module and configuring it:
knex = require('knex')({
client: 'mysql2',
connection: {
host : '<host>',
user : '<user>',
password : '<pass>',
database : '<schema>'
},
pool: {
min: 1,
max: 7
}
});
// *Resolving with the configured knex instance:
resolve(knex);
} catch(err){
// *If some error happened:
// *Rejecting with the error:
reject(err);
}
})
// *Testing the pool:
.then(knex => {
// *Appending a 'pool connection test' into the promise chain:
return new Promise((resolve, reject) => {
// *Setting a timeout flag:
let timeout = false;
// *Setting up a timeout timer:
const timer = setTimeout(() => timeout = true, knex.client.config.acquireConnectionTimeout || 60000);
// *Trying to acquire a new connection from the internal knex pool:
knex.client.pool.acquire((err, conn) => {
// *Releasing the connection:
knex.client.pool.release(conn);
// *Checking if some error has been thrown, rejecting if it has:
if(err) return reject(err);
// *Checking if the test has timed out, rejecting if it has:
if(timeout) return reject(new Error('The pool connection test has timed out'));
// *Stopping the timeout timer:
clearTimeout(timer);
// *Resolving with the knex instance:
resolve(knex);
});
});
});
}
/**
* Stops the knex connections
* @return {Promise}
*/
function stop(){
// *Checking if the knex variable is assigned, resolving if it's not:
if(!knex) return Promise.resolve();
// *Closing the connections and returning a promise:
return knex.destroy();
}
// *Exporting this module:
module.exports = { start, stop };
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment