3
\$\begingroup\$

I need to use elasticsearch in my node.js project, whose API looks like the following:

var elasticsearch = require('elasticsearch');
return new elasticsearch.Client({
  host: 'localhost:9200',
  log: 'trace'
}));

However, my elasticsearch host is stored in zookeeper, so I first need to fetch it before returning the client. This is what I've come up with so far, which seems to work:

var elasticsearch = require('elasticsearch');
var zookeeper = require('node-zookeeper-client');

var zookeeperClient = zookeeper.createClient('localhost:2181');
zookeeperClient.connect();

var exportedClient = new Promise((resolve, reject) => {
  zookeeperClient.once('connected', () => {
    zookeeperClient.getChildren('/databases/elasticsearch', function (error, children, stats) {
      if (error) {
        console.log(error.stack);
        reject(error);;
      }
      resolve(elasticsearch.Client({
        host: children[0],
        log: 'trace'
      }));
    });
  });
});

exportedClient.get = function(args) {
  return exportedClient.then((client) => {
    return client.get(args);
  });
}

exports.client = exportedClient;

And then to use it:

var elasticClient = require('./myElasticClient').client;

var get = function(id) {
  return elasticClient.get({
    index: 'product',
    type: 'products',
    id: id
  }).then(function(response) {
    return response._source;
  });
}

exports.execute = get;

I'm very new to node, but there seems like there must be a better way to do this.

\$\endgroup\$

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.