@backpack/amazon-dynamodb
️ 🗃
A lightweight utility package for working with Amazon DynamoDB.
Installing
First, ensure you have set up Nexus as private registry needed to use Backpack.
Then, install the package using npm:
bash
npm install @backpack/amazon-dynamodb
Make sure to also install the following AWS SDK libraries:
bash
npm install @aws-sdk/client-dynamodb @aws-sdk/lib-dynamodb
DynamoDbRepository
An implementation of the repository pattern, designed to abstract away direct DynamoDB interactions in your codebase.
Creating a repository
ts
import { DynamoDBClient } from "@aws-sdk/client-dynamodb";
import { DynamoDBDocumentClient } from "@aws-sdk/lib-dynamodb";
import { DynamoDbRepository } from "@backpack/amazon-dynamodb";
const client = DynamoDBDocumentClient.from(new DynamoDBClient());
const booksRepository = new DynamoDbRepository<Book>(
client,
{
tableName: 'Books', // required
// optionally, pass your Powertools Logger instance:
logger: MyLogger,
// optionally, pass a mapper to add read/write mapping functions:
itemMapper: {
// e.g. use Zod to validate data coming from DynamoDB
readItem: (item) => Book.parse(item),
// you can also use Zod for writing the data,
// to strip unknown fields and/or to have another validation guard:
writeItem: (item) => Book.parse(item),
}
}
);
Usage patterns
You can use DynamoDbRepository
in multiple ways depending on your application structure:
- Direct usage: use the repository directly in your domain layer for simple use cases.
- Composition: wrap the repository in your own repository class to customize or limit access to certain methods.
- Inheritance: extend the repository to add custom queries or override default behavior.
API reference
putItem(item)
Inserts or replaces an item using a PutCommand
.
ts
await booksRepository.putItem(myBook);
updateItem(options)
Updates an item by key using an UpdateCommand
.
ts
await booksRepository.updateItem({
Key: { id: myId },
UpdateExpression: 'set foo = :foo',
ExpressionAttributeValues: {
':foo': foo,
},
});
deleteItemById(key)
Deletes an item by key using a DeleteCommand
.
ts
await booksRepository.deleteItemById({ isbn: "9789027439642" });
getItemById()
Retrieves a single item by key using a GetCommand
.
ts
const book = await booksRepository.getItemById({ isbn: "9789027439642" });
itemExistsById()
Checks if an item exists.
ts
const exists = await booksRepository.itemExistsById({ isbn: "9789027439642" });
scanAllItems()
Returns all items using a ScanCommand
:
ts
const books = await booksRepository.scanAllItems();
queryItems()
Queries items using a QueryCommand
.
ts
const books = await booksRepository.queryItems({
KeyConditionExpression: "genre = :genre",
ExpressionAttributeValues: {
":genre": "FANTASY",
},
IndexName: "GenreIndex",
});