首页 > 解决方案 > ScanCommandOutput(AttributeValue) 映射到 Typescript 对象

问题描述

我在我的数据库中保存了几个口袋妖怪的值,例如:名称、身高、体重等,使用来自 DynamoDBDocumentClient 的命令 PutCommand

现在,我想使用 ScanCommand 从 @aws-sdk/client-dynamodb 获取我的所有数据库,并将信息解析为 Typescript 对象。

我遇到了一些麻烦,因为 JSON.parse() 在这种情况下它不起作用。

这是我数据库中的一行

id: charmander
content: {"height":{"N":"6"},"id":{"S":"charmander"},"name":{"S":"charmander"},"order":{"N":"5"},"weight":{"N":"85"}}
height: 6

这是我用来解析对象的代码(我收到一条错误消息:Type 'AttributeValue' is not assignable to type 'Pokemon'。)

const response = await this.ddbDocClient?.send(
  new ScanCommand({
    TableName: this.tableName,
  }),
);

const array =
  response?.Items?.map(
    item =>
      new PokemonDB({
        pokemon: item.content, (DOESN'T WORK)
        height: +item.height,
      }),
  ) ?? [];

这是我的方法创建:

async create(data: Pokemon): Promise<Pokemon> {
  const entity = data;

  await this.ddbDocClient?.send(
    new PutCommand({
      TableName: this.tableName,
      Item: {
        id: entity.name,
        content: entity,
        height: entity.height,
      },
    }),
  );
  return data;
}

我的对象口袋妖怪看起来像这样:

{
  "name": "ditto",
  "weight": 40,
  "id": "ditto",
  "height": 3,
  "order": 203
}

标签: typescriptamazon-dynamodbaws-sdkdynamodb-queries

解决方案


推荐阅读