AWS Lambda测试事件 -> 无法读取未定义的属性(读取'0')

huangapple go评论59阅读模式
英文:

AWS Lambda test event -> Cannot read properties of undefined (reading '0')

问题

以下是您要翻译的代码部分:

我有以下的lambda函数代码使用GET http方法试图从DynamoDB获取项目使用AWS SDK v3
函数片段-

    const { httpMethod, body, pathParameters } = event;
    const { id } = pathParameters;

    if (httpMethod === 'GET') {
      // 读取操作
      const params = {
        TableName: 'Emp_Basic',
        Key: { id }
      };
      const command = new GetItemCommand(params);
      const result = await dynamoDBClient.send(command);

      if (!result.Item) {
        return {
          statusCode: 404,
          body: JSON.stringify({ message: '未找到项目' })
        };
      }

      return {
        statusCode: 200,
        body: JSON.stringify(result.Item)
      };
    }

**我试图执行的测试事件ID是使用uuidv4()生成的 -**

{
  "httpMethod": "GET",
  "body": "",
  "pathParameters": {
    "id": "f59fb118-6aa1-47fb-8f37-3d5b023feeea"
  }
}

**我遇到的错误如下-**

{
  "statusCode": 500,
  "body": "{\"message\":\"处理请求时出错\",\"error\":\"无法读取未定义的属性(读取'0')\"}"
}

理论上DynamoDB内部应该返回项目无法弄清楚是什么原因引发了此问题

请注意,我已将HTML编码中的特殊字符(如")还原为正常的字符,以便代码更易阅读。

英文:

I have the below lambda function code with GET httpmethod and trying to get an item from DynamoDB. Using AWS SDK v3
function snippet-

const { httpMethod, body, pathParameters } = event;
const { id } = pathParameters;

if (httpMethod === 'GET') {
  // READ operation
  const params = {
    TableName: 'Emp_Basic',
    Key: { id }
  };
  const command = new GetItemCommand(params);
  const result = await dynamoDBClient.send(command);

  if (!result.Item) {
    return {
      statusCode: 404,
      body: JSON.stringify({ message: 'Item not found' })
    };
  }

  return {
    statusCode: 200,
    body: JSON.stringify(result.Item)
  };
}

The test event i'm trying to execute is, the id was generated using uuidv4() -

{
"httpMethod": "GET",
"body": "",
"pathParameters": {
"id": "f59fb118-6aa1-47fb-8f37-3d5b023feeea"
}
}

The error i'm getting is as follows-

{
"statusCode": 500,
"body": "{"message":"Error processing request","error":"Cannot read properties of undefined (reading '0')"}"
}

Ideally the item inside dynamodb should be returned. Not able to figure out whats causing this issue

答案1

得分: 2

问题在于您的代码不正确地指示了 Key 属性值,如下所示:

Key: { id }

相反,它需要指示键属性的名称、类型以及其值,具体如下:

Key: { id: { S: id } }

这表示了属性名称为 id,类型为 S(字符串)。

英文:

The problem is that your code indicates the Key attribute value incorrectly, as:

Key: { id }

Instead, it needs to indicate both the name and the type of the key attribute, as well as its value, specifically:

Key: { id: { S: id } }

That indicates the attribute name of id and the type of S (string).

huangapple
  • 本文由 发表于 2023年6月11日 22:03:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/76450847.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定