A simple wrapper to help you work with DynamoDB. Used to live as copy pasta in all my projects, decided to make it open source so I can keep making it better.
Here is a full tutorial building an example CRUD API with Simple DynamoDB 👉 Serverless Handbook: REST API
yarn add simple-dynamodb
Import as:
import * as db from "simple-dynamodb";
for best ease of use. The rest of this README assumes you're importing like this :)
These are thin wrappers on native AWS SDK DynamoDB functions. Promisified for easier use and with sensible defaults for code readability.
getItem
reads specific items from your database.
const item = await db.getItem({
TableName: process.env.ITEM_TABLE!,
Key: { itemId }
});
console.log(item.Item);
updateItem
upserts items into your database and returns the entire object by default.
const item = await db.updateItem({
TableName: process.env.ITEM_TABLE!,
Key: { itemId },
UpdateExpression: `SET ${db.buildExpression(body)}`,
ExpressionAttributeValues: {
...db.buildAttributes(body)
}
// default ReturnValues: "ALL_NEW"
});
console.log(item.Attributes);
Helper method to turn a { key: value }
object into a DynamoDB expression.
Use it in your SET
or other expressions as a string fragment. Add your own custom values on top.
UpdateExpression: `SET ${db.buildExpression(body)}`,
Helper method to turn a { key: value }
object into a DynamoDB attributes list.
Use it for your ExpressionAttributeValues
and add your own custom values on top.
ExpressionAttributeValues: {
...db.buildAttributes(body)
}
Deletes an item from your database and returns its old values by default.
const item = await db.deleteItem({
TableName: process.env.ITEM_TABLE!,
Key: { itemId }
// default ReturnValues: "ALL_OLD"
});
console.log(item.Attributes);
Used for searching through your database table.
// to get all values from a table
const result = await db.scanItems({
TableName: process.env.ITEM_TABLE!
});
console.log(result.Items);
To filter based on params, you can do something like this:
const searchBy = {
userId
}
const result = await db.scanItems({
TableName: process.env.ITEM_TABLE!,
FilterExpression: `#user = :userId`,
ExpressionAttributeNames: {
"#user": "userId"
},
ExpressionAttributeValues: {
...db.buildAttributes(searchBy)
}
}
console.log(result.Items)
👤 Swizec Teller swizec@swizec.com
- Github: @swizec
- Twitter: @swizec
- Blog: swizec.com/blog
Contributions, issues and feature requests are welcome!
Feel free to check issues page.
I am looking to support other authentication providers. Please help :)
Give a ⭐️ if this project helped you!
Copyright © 2020 Swizec Teller swizec@swizec.com.
This project is MIT licensed.