Search code examples
typescriptelasticsearchhttp-status-codesnestjs

Wrong type of @types/elasticsearch SearchResponse


When I use the ElasticsearchService of @nestjs/elasticsearch the result of the response doesnt match the type SearchResponse of @types/elasticsearch because SearchResponse is an object but I actually get an array with the SearchResponse object and a Http Status Code, does someone know how to turn this off?

Example:

[
  {
    ...,
    "aggregations": {
      "backendVersions": {
        "doc_count_error_upper_bound": 0,
        "sum_other_doc_count": 0,
        "buckets": [
          {
            "key": "1.0.0",
            "doc_count": 1
          }
        ]
      }
    }
  },
  200
]

Solution

  • The ElasticsearchService of @nestjs/elasticsearch wraps the es client with bindNodeCallback, it's explained in the doc.

    So this:

    client.search({
      index: 'my-index',
      body: { foo: 'bar' }
    }, (err, body, statusCode, headers) => {
      if (err) console.log(err)
    })
    

    Will be transformed into an observable which will emit a value with the args from the callback minus the err in an array.

    service.search({
      index: 'my-index',
      body: { foo: 'bar' }
    }).subscribe(value => {
      console.log(value); // [body, statusCode, headers]
    });
    

    You can't turn this off but you can use the elasticsearch client directly by using getClient():

    const searchResponse = await service.getClient().search({
      index: 'my-index',
      body: { foo: 'bar' }
    });
    

    Also keep in mind there will be breaking changes in @elastic/elasticsearch [7.x]:

    client.search({
      index: 'my-index',
      body: { foo: 'bar' }
    }, (err, { body, statusCode, headers, warnings }) => {
      if (err) console.log(err)
    });