在 DynamoDB 输出中使用类型

问题描述 投票:0回答:3

我想使用像这样带有

DynamoDB
的类型。

interface Custom {
  id: string,
  token: string,
}

const { Item }:GetItemOutput & { Item: Custom } = await DYNAMO_DB.get(params).promise();

我的 IDE 发出此警报。

类型“PromiseResult”不可分配给类型“GetItemOutput & { Item: Custom; }'。 类型“PromiseResult”不可分配给类型“{ Item: Custom;” }'。 属性“Item”的类型不兼容。 类型“AttributeMap”缺少类型“自定义”中的以下属性:id、tokents(2322)

如何将 typescript 与 Dynamodb 一起使用?

typescript amazon-dynamodb
3个回答
2
投票

您收到的实际对象类型是

PromiseResult
,因此以下内容将起作用

const result:PromiseResult = await DYNAMO_DB.get(params).promise();

但你并没有获得很大的好处,所以我会保留它

const result = await DYNAMO_DB.get(params).promise();

使用 TypeScript 并不意味着你必须在任何地方使用类型


2
投票

我认为这对你有用

interface Custom {
  id: string,
  token: string,
  [key: string]: AttributeValue | string
}

const {Item} = await DYNAMO_DB.get(params).promise();
const ItemWithCustomType = (Item as Custom);
ItemWithCustomType.id

0
投票

您可以使用处理类型(及更多)的库,而不是直接调用

DynamoDBDocument.get()
。 npm 包 dynamo-repo 使用起来非常简单,重量轻,你不需要担心转换。所以你的代码看起来像这样:

import { DBItemBase} from "dynamo-repo";

interface Custom extends DBItemBase {
  id: string,
  token: string,
}

const customItem = await customRepo.findItem({ id: "<custom-id-value>" });

const

customItem
已经是类型
Custom
👏😊

您只需创建

customRepo
一次:

import { DynamoDBDocument } from "@aws-sdk/lib-dynamodb";
import { Custom } from "<path to your interface>";
import { Repo } from "dynamo-repo";

export class CustomRepo extends Repo<Custom, "id"> { /* "Custom" is the interface we created above */
  constructor(ddbDocClient: DynamoDBDocument) {
    super(ddbDocClient, "custom", "id"); /* "custom" is the table name */
    this.setProjectionExpression([ /* Set all "Custom" attributes that are persisted in the table */
      "id",
      "token",
    ]);
  }
}

然后通过您的 DynamoDBDocument 实例化它:

const customRepo = new CustomRepo(DYNAMO_DB);
  • 它会自动处理特殊单词 - 例如“角色”、“计数”
  • 它可以帮助您保持实体的一致性,这对于索引来说特别方便。
  • 它简化了 dynamodb 的使用,还为您提供了其他存储库功能,例如
    addItem()
    updateItem()
    updateExpressionItem()
    searchItems()
    ,而且它们都非常易于使用。
© www.soinside.com 2019 - 2024. All rights reserved.