简体   繁体   中英

elasticsearch and typescript - bind the results to the model

I want to keep my elasticsearch api as close as possible to my model. I want to enjoy the benefit of strong typing, in the client and in the server.

I have a customer model:

export interface CustomerBody{
    name?: string;
}

export class CustomerModel implements IElModel<CustomerBody>{
    readonly index: string = "db";
    readonly type: string = "customer";
    id: string;
    body: CustomerBody = {}
}

after I save this document I run a query, and the query has different field mapping (unlike mongodb).

The result from the database is:

    "hits": [
      {
        "_index": "db",
        "_type": "customer",
        "_id": "pVM963UBtjK7RM81ZgIx",
        "_score": 1,
        "_source": {
          "name": "test"
        }
      },
      {
        "_index": "db",
        "_type": "customer",
        "_id": "p1NB63UBtjK7RM81kQIv",
        "_score": 1,
        "_source": {
          "name": "test3111111"
        }
      }
    ]

using the nodejs driver, how can I bind this result to CustomerModel[] ?
if I manage to do that, most of my logic will be strong typed.

Thanks

I solved a similar situations myself. My solution was to map the hits array into my interface, which in your case is a class.

const models: CustomerModel[] = hits.map(hit => {
  const customer = new CustomerModel();
  customer.id = hit._id;
  customer.body = hit._source;

  return customer;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM