http-aws-es icon indicating copy to clipboard operation
http-aws-es copied to clipboard

Extending HttpAmazonESConnector

Open theverything opened this issue 7 years ago • 0 comments

This isn't an issue it's more of a recommendation to anyone using this lib.

If you need any functionality in any of the pull requests you can easily just extend the HttpAmazonESConnector class to override the request method and add any functionality you need. This is what I use and it seems to be working for me.

// AsyncHttpAmazonESConnector.js

import HttpAmazonESConnector from 'http-aws-es';

function isPromise(obj) {
  return Boolean(obj)
  && (typeof obj === 'object' || typeof obj === 'function')
  && typeof obj.then === 'function';
}

class AsyncHttpAmazonESConnector extends HttpAmazonESConnector {
  request(params, cb) {
    const credentials = this.amazonES.credentials;

    if (credentials && isPromise(credentials)) {
      credentials
        .then((creds) => {
          if (creds.needsRefresh()) {
            return creds.refreshPromise();
          }
          return creds;
        })
        .then((creds) => {
          this.creds = creds;
          super.request(params, cb);
        })
        .catch((err) => {
          cb(err);
        });
    } else {
      super.request(params, cb);
    }
  }
}

export default AsyncHttpAmazonESConnector;
// esClient.js

import elasticsearch from 'elasticsearch';
import awsSDK from 'aws-sdk';
import AsyncHttpAmazonESConnector from './AsyncHttpAmazonESConnector';

const providerChain = new awsSDK.CredentialProviderChain([
  () => new awsSDK.EnvironmentCredentials('AWS'),
  () => new awsSDK.EnvironmentCredentials('AMAZON'),
  () => new awsSDK.SharedIniFileCredentials(),
  () => ((awsSDK.ECSCredentials.prototype.getECSRelativeUri() !== undefined)
    ? new awsSDK.ECSCredentials()
    : new awsSDK.EC2MetadataCredentials()),
]);

const esClient = new elasticsearch.Client({
  host: ES_HOST,
  connectionClass: AsyncHttpAmazonESConnector,
  amazonES: {
    region: AWS_REGION,
    credentials: providerChain.resolvePromise(),
  },
});

Hope this helps anyone who is stuck.

theverything avatar Mar 09 '17 17:03 theverything