🔧aws-sdk-js-v3-usage
- プラグイン
- aws-core
- ソース
- GitHub で見る ↗
説明
AWS SDK for JavaScript v3 の開発パターン。 次のような場合に使用: - `@aws-sdk/*` パッケージ(aws-sdk-js-v3)を通じて AWS サービスを利用する JavaScript または TypeScript コードを記述する場合 - JS/TS 向け AWS SDK のコンテキストにおいて、スキーマ、ランタイムバリデーション、シリアライゼーション、またはコード生成について質問される場合
原文を表示
AWS SDK for JavaScript v3 development patterns. Use when writing JavaScript or TypeScript code that uses AWS services via @aws-sdk/* packages (aws-sdk-js-v3), or when asked about schemas, runtime validation, serialization, or code generation in the context of the JS/TS AWS SDK.
ユースケース
- ✓AWS SDKをJavaScript/TypeScriptで利用するコードを書く
- ✓AWS SDK v3のスキーマについて質問される
- ✓ランタイムバリデーションの実装を相談する
- ✓シリアライゼーションについて質問される
- ✓コード生成について質問される
本文(日本語訳)
このスキルが有効な場合、コード・コメント・出力のいずれにも絵文字を使用しないこと。
AWS SDK for JavaScript v3
パッケージ構成
@aws-sdk/client-*— サービスごとに1つ。smithy-typescript によって生成され、AWSサービスおよびオペレーションと1対1で対応@aws-sdk/lib-*— 高レベルのヘルパー(例:lib-dynamodb、lib-storage)@aws-sdk/*(プレフィックスなし) — ユーティリティパッケージ(ほぼ内部用。深いパスからのインポート不可)
常にパッケージルートからインポートすること:
import { S3Client } from "@aws-sdk/client-s3"; // 正しい
// 誤り: import { S3Client } from "@aws-sdk/client-s3/dist-cjs/S3Client"
2種類のクライアントスタイル
ベアボーン(推奨 — バンドルサイズが小さい):
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
const client = new S3Client({ region: "us-east-1" });
const output = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
アグリゲート(v2スタイルだがv2ではない。バンドルサイズが大きい):
import { S3 } from "@aws-sdk/client-s3";
const client = new S3({ region: "us-east-1" });
const output = await client.getObject({ Bucket: "b", Key: "k" });
クライアント設定
v3ではグローバル設定なし — 各クライアントに設定を渡すこと。region は常に必須で、明示的に指定するか AWS_REGION 環境変数で設定する。
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);
インスタンス化後に client.config を読み取ったり変更したりしないこと — これは解決済みの形式(例: region は非同期関数になる)。references/effective-practices.md 参照。
HTTPハンドラ(@smithy/node-http-handler の NodeHttpHandler)、リトライ戦略、エンドポイントの詳細、ロギング、FIPS、デュアルスタック、プロトコル選択、S3固有のオプションについては references/clients.md を参照。
クレデンシャル
すべてのプロバイダは @aws-sdk/credential-providers から提供。クレデンシャルはクライアントごとに遅延取得・キャッシュされ、有効期限の約5分前に更新される。
// デフォルトチェーン(env → ini → IMDS/ECS)— ほとんどのNode.jsアプリで使用
const client = new S3Client({ credentials: fromNodeProviderChain() });
// ロールの引き受け(注意: STS AssumeRoleには fromTemporaryCredentials が正しい)
const client = new S3Client({
credentials: fromTemporaryCredentials({ params: { RoleArn: "arn:aws:iam::123456789012:role/MyRole" } }),
});
// 名前付きプロファイル
const client = new S3Client({ profile: "my-profile" });
マルチリージョンクライアント間でクレデンシャルとソケットプールを共有する:
const east = new S3Client({ region: "us-east-1" });
const { credentials, requestHandler } = east.config;
const west = new S3Client({ region: "us-west-2", credentials, requestHandler });
すべてのプロバイダ(Cognito、SSO、Webアイデンティティ、カスタムチェーン、STSリージョン優先度)については references/credentials.md を参照。
ストリーム(例: S3 GetObject Body)
ストリームレスポンスは必ず読み取るか破棄すること — 読み取らないとソケットが開放されない(ソケット枯渇の原因になる):
const { Body } = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
const str = await Body.transformToString(); // 文字列として読み取る
const bytes = await Body.transformToByteArray(); // Uint8Array として読み取る
// または破棄する:
await (Body.destroy?.() ?? Body.cancel?.());
ストリームは一度しか読み取れない。
ページネーター
手動でトークンを管理する代わりに paginate* 関数を使用する:
import { DynamoDBClient, paginateListTables } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});
const tableNames = [];
for await (const page of paginateListTables({ client }, {})) {
// page にはページネーションされた1件分の出力が含まれる
tableNames.push(...page.TableNames);
}
DynamoDB DocumentClient
@aws-sdk/lib-dynamodb を使用すると、AttributeValues の代わりにネイティブJSの型で操作できる:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
await client.send(new PutCommand({ TableName: "T", Item: { id: "1", name: "Alice" } }));
const { Item } = await client.send(new GetCommand({ TableName: "T", Key: { id: "1" } }));
マーシャルオプション、大きな数値(NumberValue)、ページネーション、アグリゲートクライアントについては references/dynamodb.md を参照。
S3: 署名付きURL、マルチパートアップロード、Waiter
// 署名付き GET URL
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const url = await getSignedUrl(client, new GetObjectCommand({ Bucket: "b", Key: "k" }), { expiresIn: 3600 });
// マルチパートアップロード(大きなファイル / ストリーム)
import { Upload } from "@aws-sdk/lib-storage";
const upload = new Upload({ client, params: { Bucket: "b", Key: "k", Body: stream } });
await upload.done();
// Waiter
import { waitUntilObjectExists } from "@aws-sdk/client-s3";
await waitUntilObjectExists({ client, maxWaitTime: 120 }, { Bucket: "b", Key: "k" });
presigned POST、署名付きヘッダ、Waiterオプションについては references/s3.md を参照。
エラーハンドリング
import { S3ServiceException } from "@aws-sdk/client-s3";
try {
await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
} catch (e) {
if (e?.$metadata) {
// SDK サービスエラー — $metadata.httpStatusCode、e.name、e.$response を持つ
console.error(e.name, e.$metadata.httpStatusCode);
}
}
特定のエラー型を確認する場合は e.name または instanceof を使用する。完全なパターンは references/error-handling.md を参照。
jsv3におけるランタイムバリデーション、デフォルト以外の形式へのシリアライズ、またはスキーマとは何かに関する疑問については references/schemas.md を参照。
パフォーマンス: 並列ワークロード
// maxSockets を並列バッチサイズに合わせて設定する
const client = new S3Client({
requestHandler: { httpsAgent: { maxSockets: 50 } },
cacheMiddleware: true, // カスタムミドルウェアを使用する場合はスキップ
});
ストリームのデッドロック警告: ソケット数が限られている場合、リクエストとストリームボディを別々に await しないこと — チェーンして処理すること。references/performance.md を参照。
ミドルウェア
クライアント上のすべてのコマンドにカスタムロジックを追加する:
client.middlewareStack.add(
(next, context) => async (args) => {
console.log(context.commandName, args.input);
const result = await next(args);
return result;
},
{ name: "MyMiddleware", step: "build", override: true }
);
ステップ(順序): initialize → serialize → build → finalizeRequest → deserialize
AbortController
const { AbortController } = require("@aws-sdk/abort-controller");
const { S3Client, CreateBucketCommand } = require("@aws-sdk/client-s3");
const abortController = new AbortController();
const client = new S3Client(clientParams);
const requestPromise = client.send(new CreateBucketCommand(commandParams), {
abortSignal: abortController.signal,
});
// abortSignal がすでに中断済みの場合、リクエストは作成されない。
// レスポンスが返される前に abortSignal が中断された場合、リクエストは破棄される。
abortController.abort();
// abortSignal が中断されているため、"AbortError" で失敗する。
await requestPromise;
Lambda ベストプラクティス
クライアントはハンドラの外側で初期化する(コンテナの再利用)。API呼び出しは内側で行う。非同期の初回セットアップが必要な場合は、ハンドラ内で遅延初期化フラグを使用する:
import { S3Client } from "@aws-sdk/client-s3";
const client = new S3Client({}); // 外側 — 呼び出し間で再利用される
let ready = false;
export const handler = async (event) => {
if (!ready) { await prepare(); ready = true; } // ハンドラ内で遅延1回セットアップ
// ... API呼び出しはここで
};
Lambda レイヤーとバージョニングについては references/lambda.md を参照。
Node.js バージョン要件
- v3.968.0 以降は Node.js >= 20 が必要
- v3.723.0 以降は Node.js >= 18 が必要
TypeScript
レスポンスフィールドはデフォルトで T | undefined として型付けされる。@smithy/types の AssertiveClient を使用して | undefined を除去するか、NodeJsClient / BrowserClient を使用してストリーミングblobの型を絞り込むことができる。references/typescript.md を参照。
SigV4a(S3 マルチリージョンアクセスポイント)
S3 MRAP およびその他の一部の機能には SigV4a が必要。以下のいずれか1つを正確にインストールし、副作用インポートすること:
@aws-sdk/signature-v4-crt— Node.js 専用、パフォーマンスが高い@aws-sdk/signature-v4a— Node.js + ブラウザ対応、Pure JS
import "@aws-sdk/signature-v4a"; // 副作用のみ — エクスポートされた値は不要
詳細およびMRAP ARNフォーマットについては references/sigv4a.md を参照。
原文(English)を表示
Do not use emojis in any code, comments, or output when this skill is active.
AWS SDK for JavaScript v3
Package Structure
@aws-sdk/client-*— one per service, generated by smithy-typescript; one-to-one with AWS services and operations@aws-sdk/lib-*— higher-level helpers (e.g.lib-dynamodb,lib-storage)@aws-sdk/*(no prefix) — utility packages (mostly internal; don't import deep paths)
Always import from the package root:
import { S3Client } from "@aws-sdk/client-s3"; // correct
// NOT: import { S3Client } from "@aws-sdk/client-s3/dist-cjs/S3Client"
Two Client Styles
Bare-bones (preferred — smaller bundle):
import { S3Client, GetObjectCommand } from "@aws-sdk/client-s3";
const client = new S3Client({ region: "us-east-1" });
const output = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
Aggregated (v2-style but NOT v2, larger bundle):
import { S3 } from "@aws-sdk/client-s3";
const client = new S3({ region: "us-east-1" });
const output = await client.getObject({ Bucket: "b", Key: "k" });
Client Configuration
No global config in v3 — pass config to each client. region is always required; set it explicitly or via AWS_REGION env var.
const config = { region: "us-east-1", maxAttempts: 5 };
const s3 = new S3Client(config);
const dynamo = new DynamoDBClient(config);
Do not read or mutate client.config after instantiation — it is a resolved form (e.g. region becomes an async function). See references/effective-practices.md.
For HTTP handler (NodeHttpHandler from @smithy/node-http-handler), retry strategy, endpoint details, logging, FIPS, dual-stack, protocol selection, and S3-specific options → see references/clients.md.
Credentials
All providers from @aws-sdk/credential-providers. Credentials are lazy and cached per client until ~5 min before expiry.
// Default chain (env → ini → IMDS/ECS) — use in most Node.js apps
const client = new S3Client({ credentials: fromNodeProviderChain() });
// Assume role (NOTE: fromTemporaryCredentials is correct for STS AssumeRole)
const client = new S3Client({
credentials: fromTemporaryCredentials({ params: { RoleArn: "arn:aws:iam::123456789012:role/MyRole" } }),
});
// Named profile
const client = new S3Client({ profile: "my-profile" });
Share credentials and socket pool across multi-region clients:
const east = new S3Client({ region: "us-east-1" });
const { credentials, requestHandler } = east.config;
const west = new S3Client({ region: "us-west-2", credentials, requestHandler });
For all providers (Cognito, SSO, web identity, custom chains, STS region priority) → see references/credentials.md.
Streams (e.g. S3 GetObject Body)
Always read or discard streaming responses — unread streams leave sockets open (socket exhaustion):
const { Body } = await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
const str = await Body.transformToString(); // read as string
const bytes = await Body.transformToByteArray(); // read as Uint8Array
// or discard:
await (Body.destroy?.() ?? Body.cancel?.());
Streams can only be read once.
Paginators
Use paginate* functions instead of manual token handling:
import { DynamoDBClient, paginateListTables } from "@aws-sdk/client-dynamodb";
const client = new DynamoDBClient({});
const tableNames = [];
for await (const page of paginateListTables({ client }, {})) {
// page contains a single paginated output.
tableNames.push(...page.TableNames);
}
DynamoDB DocumentClient
Use @aws-sdk/lib-dynamodb to work with native JS types instead of AttributeValues:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient, GetCommand, PutCommand } from "@aws-sdk/lib-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient({}));
await client.send(new PutCommand({ TableName: "T", Item: { id: "1", name: "Alice" } }));
const { Item } = await client.send(new GetCommand({ TableName: "T", Key: { id: "1" } }));
For marshall options, large numbers (NumberValue), pagination, and aggregated client → see references/dynamodb.md.
S3: Presigned URLs, Multipart Upload, Waiters
// Presigned GET URL
import { getSignedUrl } from "@aws-sdk/s3-request-presigner";
const url = await getSignedUrl(client, new GetObjectCommand({ Bucket: "b", Key: "k" }), { expiresIn: 3600 });
// Multipart upload (large files / streams)
import { Upload } from "@aws-sdk/lib-storage";
const upload = new Upload({ client, params: { Bucket: "b", Key: "k", Body: stream } });
await upload.done();
// Waiters
import { waitUntilObjectExists } from "@aws-sdk/client-s3";
await waitUntilObjectExists({ client, maxWaitTime: 120 }, { Bucket: "b", Key: "k" });
For presigned POST, signed headers, waiter options → see references/s3.md.
Error Handling
import { S3ServiceException } from "@aws-sdk/client-s3";
try {
await client.send(new GetObjectCommand({ Bucket: "b", Key: "k" }));
} catch (e) {
if (e?.$metadata) {
// SDK service error — has $metadata.httpStatusCode, e.name, e.$response
console.error(e.name, e.$metadata.httpStatusCode);
}
}
Check e.name or instanceof for specific error types. See references/error-handling.md for full patterns.
For runtime validation, serialization to non-default formats, or questions about what schemas are in jsv3 → see references/schemas.md.
Performance: Parallel Workloads
// Configure maxSockets to match your parallel batch size
const client = new S3Client({
requestHandler: { httpsAgent: { maxSockets: 50 } },
cacheMiddleware: true, // skip if using custom middleware
});
Streaming deadlock warning: with limited sockets, don't await the request and stream body separately — chain them. See references/performance.md.
Middleware
Add custom logic to all commands on a client:
client.middlewareStack.add(
(next, context) => async (args) => {
console.log(context.commandName, args.input);
const result = await next(args);
return result;
},
{ name: "MyMiddleware", step: "build", override: true }
);
Steps (in order): initialize → serialize → build → finalizeRequest → deserialize
Abort Controller
const { AbortController } = require("@aws-sdk/abort-controller");
const { S3Client, CreateBucketCommand } = require("@aws-sdk/client-s3");
const abortController = new AbortController();
const client = new S3Client(clientParams);
const requestPromise = client.send(new CreateBucketCommand(commandParams), {
abortSignal: abortController.signal,
});
// The request will not be created if abortSignal is already aborted.
// The request will be destroyed if abortSignal is aborted before response is returned.
abortController.abort();
// This will fail with "AbortError" as abortSignal is aborted.
await requestPromise;
Lambda Best Practices
Initialize clients outside the handler (container reuse), make API calls inside. For one-time async setup, use a lazy init flag inside the handler:
import { S3Client } from "@aws-sdk/client-s3";
const client = new S3Client({}); // outside — reused across invocations
let ready = false;
export const handler = async (event) => {
if (!ready) { await prepare(); ready = true; } // lazy one-time setup inside handler
// ... API calls here
};
See references/lambda.md for Lambda layers and versioning.
Node.js Version Requirements
- v3.968.0+ requires Node.js >= 20
- v3.723.0+ requires Node.js >= 18
TypeScript
Response fields are typed as T | undefined by default. Use AssertiveClient from @smithy/types to remove | undefined, or NodeJsClient / BrowserClient to narrow streaming blob types. See references/typescript.md.
SigV4a (S3 Multi-Region Access Points)
S3 MRAP and certain other features require SigV4a. You must install and side-effect-import exactly one of:
@aws-sdk/signature-v4-crt— Node.js only, better performance@aws-sdk/signature-v4a— Node.js + browsers, pure JS
import "@aws-sdk/signature-v4a"; // side-effect only — no exported values needed
See references/sigv4a.md for full details and MRAP ARN format.
原文・著作権は Anthropic および各プラグイン作者に帰属します。日本語訳は Claude API による自動翻訳です。