sam-goodwin / typesafe-dynamodb

TypeSafe type definitions for the AWS DynamoDB API
Apache License 2.0
205 stars 11 forks source link

Struggling to understand how to use TypeSafeDocumentClientV3 #44

Closed gpitot closed 1 year ago

gpitot commented 1 year ago
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";

import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { TypeSafeDocumentClientV3 } from "typesafe-dynamodb/lib/document-client-v3";
import { TypeSafeGetDocumentCommand } from "typesafe-dynamodb/lib/get-document-command";

const client = new DynamoDBClient({});

interface Users<UserID extends string = string> {
  pk: `USERS#${UserID}`;
  sk: `USERS#${UserID}`;
  firstname: string;
}

const docClient = DynamoDBDocumentClient.from(
  client
) as TypeSafeDocumentClientV3<Users, "pk", "sk">;

const MyGetItemCommand = TypeSafeGetDocumentCommand<Users, "pk", "sk">();

const res = await docClient.send(
  new MyGetItemCommand({
    TableName: "a",
    Key: {
      pk: "USERS#a",
      sk: "USERS#b",
    },
  })
);
console.log(res.Item?.attributes); // never

res.Item is undefined and I cannot access my expected properties on it, how can I access pk/sk/firstname here?

gpitot commented 1 year ago

same issue as https://github.com/functionless/typesafe-dynamodb/issues/41

sam-goodwin commented 1 year ago

Yeah this is a problem with type narrowing - if they keys are literal strings then typescript doesn't properly narrow the type.

You can workaround it by putting the "a" string as a variable and then splicing it in.

const a = "a" as string;

const res = await docClient.send(
  new MyGetItemCommand({
    TableName: "a",
    Key: {
      pk: "USERS#${a}",
      sk: "USERS#b",
    },
  })
);

You may also be able to splice like this:

`USERS#${"a" as string}`

Not much we can do here without improvements from typescript.

In the general case where the key is constructed from an input argument, it should work.

github-actions[bot] commented 1 year ago

This issue is now marked as stale because it hasn't seen activity for a while. Add a comment or it will be closed soon. If you wish to exclude this issue from being marked as stale, add the "backlog" label.

sam-goodwin commented 1 year ago

Bumping to remain open

github-actions[bot] commented 1 year ago

This issue is now marked as stale because it hasn't seen activity for a while. Add a comment or it will be closed soon. If you wish to exclude this issue from being marked as stale, add the "backlog" label.