api_client.js 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. 'use strict';
  2. const cluster = require('./');
  3. const utils = require('./utils');
  4. const Base = require('sdk-base');
  5. const is = require('is-type-of');
  6. class APIClientBase extends Base {
  7. constructor(options) {
  8. options = options || {};
  9. super(options);
  10. const wrapper = (options.cluster || cluster)(
  11. this.DataClient, this.clusterOptions
  12. );
  13. for (const from in this.delegates) {
  14. const to = this.delegates[from];
  15. wrapper.delegate(from, to);
  16. }
  17. this._client = wrapper.create(options);
  18. utils.delegateEvents(this._client, this);
  19. if (!options.initMethod) {
  20. this._client.ready(err => {
  21. this.ready(err ? err : true);
  22. });
  23. }
  24. }
  25. get isClusterClientLeader() {
  26. return this._client.isClusterClientLeader;
  27. }
  28. close() {
  29. if (is.function(this._client.close)) {
  30. return this._client.close();
  31. }
  32. return cluster.close(this._client);
  33. }
  34. get DataClient() {
  35. /* istanbul ignore next */
  36. throw new Error('[APIClient] DataClient is required');
  37. }
  38. /**
  39. * the cluster options
  40. *
  41. * @property {Object} APIClientBase#clusterOptions
  42. */
  43. get clusterOptions() {
  44. /* istanbul ignore next */
  45. return {};
  46. }
  47. /**
  48. * the delegates map
  49. *
  50. * @example
  51. * ---------------------------
  52. * delegates => {
  53. * subscribe: 'subscribe',
  54. * foo: 'invoke',
  55. * }
  56. *
  57. * @property {Object} APIClientBase#delegates
  58. */
  59. get delegates() {
  60. /* istanbul ignore next */
  61. return {};
  62. }
  63. }
  64. module.exports = APIClientBase;