use-dynamodb
v1.0.0
Published
A TypeScript library that provides a simplified interface for interacting with Amazon DynamoDB, using the AWS SDK v3.
Downloads
69
Readme
Use DynamoDB
A TypeScript library that provides a simplified interface for interacting with Amazon DynamoDB, using the AWS SDK v3.
🚀 Features
- ✅ Support for CRUD operations (Create, Read, Update, Delete)
- 🔍 Support for local and global secondary indexes
- 📦 Batch operations (batch write and delete)
- 🔎 Optimized queries with filtering
- 🔒 Conditional updates
- 📄 Pagination support
- 🔄 Upsert support
- ⏱️ Automatic timestamp management
📦 Installation
yarn add use-dynamodb
🛠️ Usage
Initialization
import Dynamodb from 'use-dynamodb';
const dynamodb = new Dynamodb({
accessKeyId: 'YOUR_ACCESS_KEY',
secretAccessKey: 'YOUR_SECRET_KEY',
region: 'us-east-1',
table: 'YOUR_TABLE_NAME',
schema: { partition: 'pk', sort: 'sk' },
indexes: [
{
name: 'ls-index',
partition: 'pk',
sort: 'lsiSk',
type: 'S'
},
{
name: 'gs-index',
partition: 'gsiPk',
sort: 'gsiSk',
type: 'S'
}
]
});
Basic Operations
📝 Create/Update Item (Put)
const item = await dynamodb.put({
pk: 'user#123',
sk: 'profile',
name: 'John Doe',
email: '[email protected]'
});
📖 Get Item
const item = await dynamodb.get({
pk: 'user#123',
sk: 'profile'
});
🔄 Update Item
const updatedItem = await dynamodb.update(
{
pk: 'user#123',
sk: 'profile'
},
{
updateFn: item => ({
...item,
email: '[email protected]'
})
}
);
🗑️ Delete Item
const deletedItem = await dynamodb.delete({
pk: 'user#123',
sk: 'profile'
});
Advanced Query Operations
🔍 Fetch (Query) Items
const { items, count, lastEvaluatedKey } = await dynamodb.fetch({
pk: 'user#123'
});
🔎 Fetch with Filter
const { items, count, lastEvaluatedKey } = await dynamodb.fetch(
{ pk: 'user#123' },
{
attributeNames: { '#foo': 'foo' },
attributeValues: { ':foo': 'foo-0' },
filterExpression: '#foo = :foo'
}
);
📄 Fetch with Pagination
const { items, count, lastEvaluatedKey } = await dynamodb.fetch(
{ pk: 'user#123' },
{
limit: 10,
startKey: lastEvaluatedKey // from previous query
}
);
Batch Operations
📦 Batch Write
const items = [
{ pk: 'user#1', sk: 'profile', name: 'User 1' },
{ pk: 'user#2', sk: 'profile', name: 'User 2' }
];
await dynamodb.batchWrite(items);
🗑️ Batch Delete
await dynamodb.batchDelete({ pk: 'user#123' });
Using Indexes
🔍 Query using Local Secondary Index
const { items, count, lastEvaluatedKey } = await dynamodb.fetch({
pk: 'user#123',
lsiSk: 'lsi-value'
});
🔎 Query using Global Secondary Index
const { items, count, lastEvaluatedKey } = await dynamodb.fetch({
gsiPk: 'gsi-partition-value',
gsiSk: 'gsi-sort-value'
});
🧪 Testing
This library includes a comprehensive set of tests. To run the tests:
- Set the required environment variables:
export AWS_REGION='us-east-1'
export AWS_ACCESS_KEY='YOUR_ACCESS_KEY'
export AWS_SECRET_KEY='YOUR_SECRET_KEY'
- Run the tests:
yarn test
Make sure to replace 'YOUR_ACCESS_KEY' and 'YOUR_SECRET_KEY' with your actual AWS credentials.