Advertisement
Guest User

Untitled

a guest
Mar 13th, 2017
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.33 KB | None | 0 0
  1. /**
  2. * The knex instance
  3. */
  4. let knex = null;
  5.  
  6.  
  7.  
  8. /**
  9. * Starts a knex instance and test its connections pool
  10. * @return {Promise<knex>} A promise that resolves with the knex instance, or rejects if some error happened
  11. */
  12. function start(){
  13.  
  14. // *Returning a promise chain:
  15. return new Promise((resolve, reject) => {
  16. // *Trying to get a knex instance:
  17. try{
  18. // *Requiring the knex module and configuring it:
  19. knex = require('knex')({
  20. client: 'mysql2',
  21. connection: {
  22. host : '<host>',
  23. user : '<user>',
  24. password : '<pass>',
  25. database : '<schema>'
  26. },
  27. pool: {
  28. min: 1,
  29. max: 7
  30. }
  31. });
  32.  
  33. // *Resolving with the configured knex instance:
  34. resolve(knex);
  35. } catch(err){
  36. // *If some error happened:
  37. // *Rejecting with the error:
  38. reject(err);
  39. }
  40. })
  41.  
  42. // *Testing the pool:
  43. .then(knex => {
  44. // *Appending a 'pool connection test' into the promise chain:
  45. return new Promise((resolve, reject) => {
  46. // *Setting a timeout flag:
  47. let timeout = false;
  48.  
  49. // *Setting up a timeout timer:
  50. const timer = setTimeout(() => timeout = true, knex.client.config.acquireConnectionTimeout || 60000);
  51.  
  52. // *Trying to acquire a new connection from the internal knex pool:
  53. knex.client.pool.acquire((err, conn) => {
  54. // *Releasing the connection:
  55. knex.client.pool.release(conn);
  56.  
  57. // *Checking if some error has been thrown, rejecting if it has:
  58. if(err) return reject(err);
  59.  
  60. // *Checking if the test has timed out, rejecting if it has:
  61. if(timeout) return reject(new Error('The pool connection test has timed out'));
  62.  
  63. // *Stopping the timeout timer:
  64. clearTimeout(timer);
  65.  
  66. // *Resolving with the knex instance:
  67. resolve(knex);
  68. });
  69.  
  70. });
  71.  
  72. });
  73.  
  74. }
  75.  
  76.  
  77.  
  78. /**
  79. * Stops the knex connections
  80. * @return {Promise}
  81. */
  82. function stop(){
  83. // *Checking if the knex variable is assigned, resolving if it's not:
  84. if(!knex) return Promise.resolve();
  85.  
  86. // *Closing the connections and returning a promise:
  87. return knex.destroy();
  88. }
  89.  
  90.  
  91.  
  92. // *Exporting this module:
  93. module.exports = { start, stop };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement