1
0

Proxy環境下でAWS SDKv3 for JavaScriptを使う

Posted at

AWS SDKでAmazon CloudSearchを利用する際にどハマリしたので備忘録として作成。
ずっと認証情報が渡せてないと勘違いしてたのは内緒

環境

$ node --version
v21.7.1
$ yarn --version
1.22.19

必要パッケージのインストール

$ yarn add @aws-sdk/client-cloudsearch-domain @aws-sdk/credential-provider-ini @smithy/node-http-handler https-proxy-agent dotenv
  • @aws-sdk/client-cloudsearch-domain : Amazon CloudSearchに検索リクエストを実行
  • @aws-sdk/credential-provider-ini : ~/.aws/credentialsからAWSの認証情報を読み込む
  • @smithy/node-http-handler : HTTPリクエストハンドラ
  • https-proxy-agent : プロキシ経由で通信を行う
  • dotenv : .env.localから設定情報を読み込む

実装例

接続で利用する認証情報は~/.aws/credentialsに予め設定しておきます。

~/.aws/credentials
[default]
aws_access_key_id = xxxxxxxxxxxxx
aws_secret_access_key = xxxxxxxxxxxxxxxxxxxxxxxxxx

.env.localに設定したPROXYからプロキシ情報を読み込むものとします。
今回は接続に必要な情報もここで定義します。

.env.local
PROXY=http://example.com:port
AWS_REGION=your-region
ENDPOINT=https://search-your-cloudsearch-domain.your-region.cloudsearch.amazonaws.com
App.ts
import { CloudSearchDomainClient, SearchCommand } from "@aws-sdk/client-cloudsearch-domain";
import * as dotenv from 'dotenv';
import { fromIni } from '@aws-sdk/credential-provider-ini';

import { NodeHttpHandler } from "@smithy/node-http-handler";
import { HttpsProxyAgent } from "https-proxy-agent";

// .env.localの内容を読み込む
dotenv.config({ path: '.env.local' });
const region: string = process.env.AWS_REGION ?? '';
const endpoint: string = process.env.ENDPOINT ?? '';
const proxy: string = process.env.PROXY ?? '';

// プロキシ情報の設定
const agent = new HttpsProxyAgent(proxy);

// 認証情報の読み込み
const credentials = fromIni({ profile: 'default' });

// CloudSearchDomainClientの設定。
let csClient: CloudSearchDomainClient | null = null;

// まだ一度も呼びだされていない場合はcsClientを初期化し返却、
// 呼び出し済の場合は初期化済みのcsClientを返却する。
async function getClient(): Promise<CloudSearchDomainClient> {
  if (!csClient) {
    const creds = await credentials();
    csClient = new CloudSearchDomainClient({
      // requestHandlerにプロキシ設定済みのHttpsProxyAgentを渡す。
      requestHandler: new NodeHttpHandler({
        httpAgent: agent,
        httpsAgent: agent,
      }),
      // 接続に必要な情報をここで渡す
      endpoint: endpoint,
      region: region,
      credentials: creds,
    });
  }
  return csClient;
}

// 検索結果をコンソールに出力する。
async function search(query: string) {
    const client = await getClient();
    const command = new SearchCommand({
      query: query,
    });

    try {
      const response = await client.send(command);
      // 検索結果はresponse.hits?.hit[]に格納されます
      console.log(JSON.stringify(response));
    } catch (error) {
      console.log(JSON.stringify(error));
    }
}

search('hogehoge');

実行結果

{
	"$metadata": {
		"httpStatusCode": 200,
		"attempts": 1,
		"totalRetryDelay": 0
	},
	"hits": {
		"found": xx,
		"start": 0,
		"hit": [
			{
				"id": "id",
				"fields": {...}
			}, ...
		]
	}
}
1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0