You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用opensearch-js完成请求签名?aws-es-connection类型不兼容如何解决?

问题原因

你遇到的类型不兼容问题不是解构写法错误导致的,核心原因是@acuris/aws-es-connection包原本是为Elasticsearch官方JS客户端开发的适配工具,它导出的Connection、ConnectionPool等类的类型定义和@opensearch-project/opensearch客户端内置的同名类类型不匹配。

解决方法

方案1:临时绕开类型报错

通过类型断言忽略类型校验即可快速解决报错,适合临时调试场景:

import {
  createAWSConnection,
  awsGetCredentials,
} from '@acuris/aws-es-connection';
import { Client, ClientOptions } from "@opensearch-project/opensearch";
import { esConfig } from "./config";

export const getClient = async () => {
  const awsCredentials = await awsGetCredentials();
  const AWSConnection = createAWSConnection(awsCredentials);
  const client = new Client({
    ...AWSConnection,
    node: esConfig.uri
  } as ClientOptions); // 新增类型断言绕开校验
  return client;
};

注意:该方案仅解决类型报错,若两个客户端底层API存在差异,可能触发运行时错误,不推荐长期使用。

方案2:使用Opensearch官方适配的AWS签名方案(推荐)

不用第三方适配包,自行实现支持AWS SigV4签名的Connection类,完全兼容opensearch-js的类型定义:

  1. 首先安装依赖
    npm install @aws-sdk/credential-provider-node @aws-sdk/signature-v4 @aws-crypto/sha256-browser @aws-sdk/protocol-http
  2. 代码实现
import { Client, Connection } from "@opensearch-project/opensearch";
import { defaultProvider } from "@aws-sdk/credential-provider-node";
import { SignatureV4 } from "@aws-sdk/signature-v4";
import { Sha256 } from "@aws-crypto/sha256-browser";
import { HttpRequest } from "@aws-sdk/protocol-http";
import { esConfig } from "./config";

// 替换为你的AWS服务部署区域
const AWS_REGION = "us-east-1";

class AWSV4SignerConnection extends Connection {
  async request(params: any, callback: any) {
    const credentials = await defaultProvider()();
    const signer = new SignatureV4({
      credentials,
      region: AWS_REGION,
      service: "es",
      sha256: Sha256,
    });

    const request = new HttpRequest({
      hostname: this.url.hostname,
      path: params.path,
      method: params.method,
      body: params.body,
      headers: {
        ...params.headers,
        host: this.url.hostname,
      },
    });

    const signedRequest = await signer.sign(request);
    params.headers = signedRequest.headers;
    return super.request(params, callback);
  }
}

export const getClient = () => {
  return new Client({
    node: esConfig.uri,
    Connection: AWSV4SignerConnection,
  });
};

该方案完全适配opensearch官方客户端的类型定义,没有第三方依赖的版本兼容风险,稳定性更高。

内容的提问来源于stack exchange,提问作者conner.xyz

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.25 19:45:03