Using DynamoDB
DynamoDB is a fully managed NoSQL database service offered by AWS. It's designed for high-performance, low-latency applications that need to scale seamlessly.
Adding your DynamoDB table to CDK
To create your DynamoDB table, you need to define a CDK construct for it.
Our recommendation is to use the Table
construct from aws-cdk-lib/aws-dynamodb
.
import { Stack, StackProps } from 'aws-cdk-lib';
import { Construct } from 'constructs';
import { NodejsFunction, OutputFormat } from 'aws-cdk-lib/aws-lambda-nodejs';
import { AttributeType, BillingMode, Table } from "aws-cdk-lib/aws-dynamodb";
export class AppStack extends Stack {
constructor(scope: Construct, id: string, props?: StackProps) {
super(scope, id, props);
// const myLambdaFunction = ...
const myTable = new Table(this, id, {
partitionKey: { name: "id", type: AttributeType.STRING },
billingMode: BillingMode.PAY_PER_REQUEST
});
// since the table name is created dynamically,
// you may want to pass it to your lambda as environment variable:
// myLambdaFunction.addEnvironment("MY_TABLE_NAME", myTable.tableName);
}
}
Recommended settings for this construct can be found on our CDK snippet page.
Writing a repository
To interact with DynamoDB, we recommend using @aws-sdk/lib-dynamodb
. This library simplifies the process by removing the need to manually marshal and unmarshal DynamoDB attribute values.
If you prefer, you can even use the default repository implementation from @backpack/amazon-dynamodb
, which streamlines common DynamoDB operations:
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { DynamoDbRepository } from "@backpack/amazon-dynamodb";
// Create a client
const client = DynamoDBDocumentClient.from(new DynamoDBClient());
// Define a repository
const booksRepository = new DynamoDbRepository<Book>(
client,
{ tableName: 'Books' }
);
// Retrieve an item by ID
const book = await booksRepository.getItemById({ isbn: "9789027439642" });
Check out @backpack/amazon-dynamodb
to learn more. Or have a look at the Bookstore REST API demo.