1.0.0 โข Published 8 months ago
use-dynamodb v1.0.0
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: 'john@example.com'
});
๐ 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: 'newemail@example.com'
})
}
);
๐๏ธ 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.
๐ Acknowledgements
1.0.0
8 months ago