pool-cluster-callback.js 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. 'use strict';
  2. const PoolCluster = require('./pool-cluster');
  3. const util = require('util');
  4. /**
  5. * Create a new Cluster.
  6. * Cluster handle pools with patterns and handle failover / distributed load
  7. * according to selectors (round robin / random / ordered )
  8. *
  9. * @param args cluster argurments. see pool-cluster-options.
  10. * @constructor
  11. */
  12. function PoolClusterCallback(args) {
  13. PoolCluster.call(this, args);
  14. this.setCallback();
  15. const initialGetConnection = this.getConnection.bind(this);
  16. const initialEnd = this.end.bind(this);
  17. /**
  18. * End cluster (and underlying pools).
  19. *
  20. * @param callback - not mandatory
  21. */
  22. this.end = (callback) => {
  23. if (callback && typeof callback !== 'function') {
  24. throw new Error('callback parameter must be a function');
  25. }
  26. const endingFct = callback ? callback : () => {};
  27. initialEnd()
  28. .then(() => {
  29. endingFct();
  30. })
  31. .catch(endingFct);
  32. };
  33. /**
  34. * Get connection from available pools matching pattern, according to selector
  35. *
  36. * @param pattern pattern filter (not mandatory)
  37. * @param selector node selector ('RR','RANDOM' or 'ORDER')
  38. * @param callback callback function
  39. */
  40. this.getConnection = (pattern, selector, callback) => {
  41. let pat = pattern,
  42. sel = selector,
  43. cal = callback;
  44. if (typeof pattern === 'function') {
  45. pat = null;
  46. sel = null;
  47. cal = pattern;
  48. } else if (typeof selector === 'function') {
  49. sel = null;
  50. cal = selector;
  51. }
  52. const endingFct = cal ? cal : (conn) => {};
  53. initialGetConnection(pat, sel, endingFct);
  54. };
  55. }
  56. util.inherits(PoolClusterCallback, PoolCluster);
  57. module.exports = PoolClusterCallback;