Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extending elasticsearch.Client on an ES6 code #516

Closed
ThiagoMiranda opened this issue Mar 9, 2017 · 4 comments
Closed

Extending elasticsearch.Client on an ES6 code #516

ThiagoMiranda opened this issue Mar 9, 2017 · 4 comments

Comments

@ThiagoMiranda
Copy link

ThiagoMiranda commented Mar 9, 2017

Hi..

Probably I'm doing something wrong ( or getting the wrong idea on the extends implementation ) but why can't I add methods extending the elasticsearch.Client class?

class MyClass extends elasticsearch.Client {
    
    constructor(config) {
        super(config);       

       this.testConnection(); //-> gives an this.testConnection is undefined
    }

    testConnection() {
        this.ping({
            requestTimeout: 30000,
        }, (error) => {
            if(error) console.error('Elastic search is out');
            if(!error) {
                console.log('Conected');
            }
        });
    }
}

const client = new MyClass({
    host: 'my_host', 
    log: 'info'
});

MyClass.testConnection(); //also an "undefined" error

Ps: The super method is called since I have a "Elastic info connected" message

@Mattchewone
Copy link

@ThiagoMiranda don't you need to call client.testConnection() as opposed to MyClass.testConnection()?

@ThiagoMiranda
Copy link
Author

@Mattchewone sorry I've changed some of the code variables name but it gives me the same error

@spalger
Copy link
Contributor

spalger commented Mar 16, 2017

Sorry, but the elasticsearch.Client constructor isn't inheritable. It actually creates a new constructor inside itself (based on the chosen apiVersion) and then returns an instance of that constructor (see https://github.com/elastic/elasticsearch-js/blob/master/src/lib/client.js#L101).

To extend the API I suggest using a plugin, like so:

const customApiPlugin = Client =>
  class CustomClient extends Client {
    testConnection() {
      this.ping({
        requestTimeout: 30000,
      }, (error) => {
        if(error) console.error('Elastic search is out');
        if(!error) {
          console.log('Conected');
        }
      });
    }
  }

const client = new elasticsearch.Client({
  plugins: [customApiPlugin]
});

client.testConnection();

@spalger spalger closed this as completed Mar 16, 2017
@ThiagoMiranda
Copy link
Author

@spalger thanks I'll try that

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants