如何正确地将返回类型添加到 aws-sdk DynamoDb Send 命令

Mat*_*ijs 5 amazon-dynamodb typescript aws-sdk

当我使用新的 v3 aws-sdk 执行 DynamoDB Get 时,我试图将泛型类型重新作为我的 OutputType 的一部分。

我的函数如下所示:

public async getItem<T>(data: GetItemCommandInput) {
  const command = new GetItemCommand({
    ...data
  });
  return await this.dbClient.send<GetItemCommand, T>(command);
}
Run Code Online (Sandbox Code Playgroud)

Typescript 不满意将 T 放入 Send 调用中。看看打字稿的定义,它非常混乱,我不明白他们在做什么。第一个 TypeSend期望的类型是ClientInput,第二个类型是ClientOutput。看看这个定义,ClientOutput我的下巴都张开了:

ClientOutput extends MetadataBearer, ResolvedClientConfiguration extends SmithyResolvedConfiguration<HandlerOptions>> implements IClient<ClientInput, ClientOutput, ResolvedClientConfiguration>
Run Code Online (Sandbox Code Playgroud)

....好吧,他们失去了我。

通常我会期望类似的东西:

 await this.dbClient.send<GetItemCommandInput, T>(command);
or 
return await this.dbClient.send<GetItemCommandInput, GetItemCommandOutput<LegalAccount>>(command);
Run Code Online (Sandbox Code Playgroud)

GetItemCommandOutput不允许通用。

查看源代码,我看到:

export interface GetItemOutput {
    /**
     * <p>A map of attribute names to <code>AttributeValue</code> objects, as specified
     *             by <code>ProjectionExpression</code>.</p>
     */
    Item?: {
        [key: string]: AttributeValue;
    };
Run Code Online (Sandbox Code Playgroud)

我的全部观点是,当我获得查询结果时,我知道输出中的 Item 是 T 类型。AWS 是否忘记了这一点,或者我是否遗漏了某些内容。文档完全没有预期的帮助:(

小智 1

我不确定这是否可以帮助您,我遇到了与您类似的问题,我终于找到了这个客户

使用这个客户端,我能够执行与旧客户端类似的查询aws-sdk

您必须像这样设置 DynamoDB 客户端:

import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
const dynamoClient = new DynamoDBClient();
const ddbDocClient = DynamoDBDocumentClient.from(dynamoClient);
Run Code Online (Sandbox Code Playgroud)

你的函数可能会变成这样:

import { GetCommand, GetCommandInput } from "@aws-sdk/lib-dynamodb";
// ...
public async getItem<T>(data: GetCommandInput) {
  const command = new GetCommand({
    ...data
  });
  return await this.ddbDocClient.send(command) as Omit<GetCommandOutput, "Item"> & { Item: T };
}
Run Code Online (Sandbox Code Playgroud)

正如文档所述:

文档客户端通过抽象属性值的概念,简化了 Amazon DynamoDB 中项目的使用。

然后您可以推断类型并期望它正常工作。

  • 这本质上什么也没做,因为你可以将这种类型转换为几乎任何东西,因为它首先是如此通用。你可以传入一个“type Foo = { foo: string }”,这会起作用,即使它检索的记录可能不是那样的。 (6认同)