sudo-suhas/elastic-builder

Add arbitrary key/ value pairs to request body

franz-josef-kaiser opened this issue · 3 comments

Szenario

For a provider specific implementation, we need to add some additional arbitrary key/ value pairs to a esb.requestBodySearch() object.

Example

const query = esb.requestBodySearch()
    .query( esb.matchAllQuery() )
    .sort( esb.sort('created_at', 'desc') )
    .arbitrayFields( {
        raw: true,
        page: 1,
        per_page: 100,
        include: [
            "name",
            "created_at",
            "email",
            "…",
        ]
    } );

The only "solution" we could come up so far (we are not using TypeScript) is to convert the requestBody to JSON and extending the object itself. We really dislike this approach as we want to pass around esb objects, rather than the JSON string to have all of the packages/ libraries possibilities at hand when we need it.

let requestBody = query.toJSON();
Object.assign( requestBody, {
    raw: true,
    page: 1,
    per_page: 100,
    include: [
        "name",
        "created_at",
        "email",
        "…",
    ]
} );

Thanks!

@franz-josef-kaiser I understand and am open to a PR which introduces the functionality. But the next question is whether all classes defined in elastic-builder should support arbitrary fields.

@franz-josef-kaiser Here's a simple way to solve your problem(extend the class):

const esb = require("elastic-builder");

class RequestBodySearch extends esb.RequestBodySearch {
  _extra = null;

  extra(extra) {
    this._extra = extra;
    return this;
  }

  toJSON() {
    const body = super.toJSON();
    Object.assign(body, this._extra);
    return body;
  }
}

const reqBody = new RequestBodySearch()
  .query(esb.matchAllQuery())
  .sort(esb.sort("created_at", "desc"))
  .extra({
    raw: true,
    page: 1,
    per_page: 100,
    include: ["name", "created_at", "email", "…"]
  });

console.log(reqBody.toJSON());
// {
//   query: { match_all: {} },
//   sort: [ { created_at: 'desc' } ],
//   raw: true,
//   page: 1,
//   per_page: 100,
//   include: [ 'name', 'created_at', 'email', '…' ]
// }

@sudo-suhas I completely missed your answer while I had a deep dive into another project. Will give this a test run soon and leave some feedback here. Thanks a lot!