AWS SDK for JavaScript v3
DynamoDB Document Clientを使ったv2->v3への移行で大ハマりしました。パラメータは変わらないのになぜか以下のエラーが出てネットを調べまくりましたが原因が分からず。
エラー内容
err: TypeError: Cannot read properties of undefined (reading '0')
at AttributeValue.visit (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/models/models_0.js:632:40)
at se_AttributeValue (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:2948:38)
at /Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:3149:20
at Array.reduce (<anonymous>)
at se_ExpressionAttributeValueMap (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:3145:34)
at ExpressionAttributeValues (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:3352:43)
at applyInstruction (/Users/***/Test/aws/dynamo/node_modules/@smithy/smithy-client/dist-cjs/object-mapping.js:73:33)
at take (/Users/***/Test/aws/dynamo/node_modules/@smithy/smithy-client/dist-cjs/object-mapping.js:44:9)
at se_QueryInput (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:3346:37)
at se_QueryCommand (/Users/***/Test/aws/dynamo/node_modules/@aws-sdk/client-dynamodb/dist-cjs/protocols/Aws_json1_0.js:273:27)
}
原因
結局、試行錯誤した結果がこれ。
元のコード
const { DynamoDBClient, QueryCommand } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient } = require("@aws-sdk/lib-dynamodb");
// (中略)
const ddbClient = new DynamoDBClient({ credentials });
const ddbDocClient = DynamoDBDocumentClient.from(ddbClient);
ddbDocClient.send(new QueryCommand(params))
.then((value) => {
console.log(value);
}).catch((err) => {
console.log({ params, err });
});
修正コード
const { DynamoDBClient } = require("@aws-sdk/client-dynamodb");
const { DynamoDBDocumentClient, QueryCommand } = require("@aws-sdk/lib-dynamodb");
// (中略)
const ddbClient = new DynamoDBClient({ credentials });
const ddbDocClient = DynamoDBDocumentClient.from(ddbClient);
ddbDocClient.send(new QueryCommand(params))
.then((value) => {
console.log(value);
}).catch((err) => {
console.log({ params, err });
});
1,2行目を見ていただきたいのですが、QueryCommand
はclient-dynamodb
とlib-dynamodb
のどちらにも存在しており、間違いに気付きにくいので要注意です。なお、TypeScriptなら型チェックで容易に見つかるのでこんなことは起きないです。