简体   繁体   English

如何使新的 elasticsearch node.js 客户端仅在承诺中返回正文?

[英]How to make the new elasticsearch node.js client only returns body in promises?

"The returned value of an API call will no longer be the body, statusCode, and headers for callbacks, and only the body for promises. The new returned value will be a unique object containing the body, statusCode, headers, warnings, and meta, for both callback and promises." “API 调用的返回值将不再是回调的主体、状态代码和标头,而只是承诺的主体。新的返回值将是一个唯一的 object,包含主体、状态代码、标头、警告和元数据, 对于回调和承诺。"

This is a problem if I stringify and store the result in redis (now I will need to JSON parse when I get the value back from redis).如果我将结果字符串化并将其存储在 redis 中,这是一个问题(现在,当我从 redis 取回值时,我需要解析 JSON)。 Is there anyway I can switch on "body only" mode on promises?无论如何我可以在承诺上打开“仅限正文”模式吗?

Unforntunately, no.不幸的是,没有。 There is no way to only receive only the body.没有办法只接受身体。 As you mentioned this would be the response,正如你所提到的,这将是回应,

{
  body: object | boolean
  statusCode: number
  headers: object
  warnings: [string]
  meta: object
}

Best you can do it before you store the response in Redis you can store it like this,最好在将响应存储在 Redis 之前执行此操作,您可以像这样存储它,

const {body} = await client.search({
  index: 'my-index',
  body: { foo: 'bar' }
})
// Now you can store the body in Redis

Or when you fetch the response object from Redis you can do this,或者,当您从 Redis 获取响应 object 时,您可以这样做,

const {body}=JSON.parse(fetchFromRedis(id));

As a workaround you could overwrite/proxy the search() method of your Client -instance.作为一种解决方法,您可以覆盖/代理您的Client -instance 的search()方法。 So you could define your proxy with something like:因此,您可以使用以下内容定义您的代理:

function initializeSearchProxy(client) {
    const origSearch = client.search;
    client.search = async function () {
        const {body} = await origSearch.apply(this, arguments);
        return body;
    }
}

Then initialize your search-proxy after requiring and instantiating the elasticsearch- Client ,然后在需要并实例化 elasticsearch- Client之后初始化您的 search-proxy,

const {Client} = require('@elastic/elasticsearch');
const client = new Client({node: 'http://localhost:9200'});
initializeSearchProxy(client);
...
// all client.search calls now return the body directly

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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