Last active
June 4, 2021 09:15
-
-
Save avtaniket/f90701703aa0a6ea480fcaa3706d94f9 to your computer and use it in GitHub Desktop.
DynamoDB and Node.js - Complete Cheat Sheet
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
### Setup | |
const AWS = require("aws-sdk") // Or use `import` syntax for Typescript and newer ES versions | |
const dynamoDB = new AWS.DynamoDB({ | |
region: "us-east-1" | |
}) | |
// Or | |
const documentClient = new AWS.DynamoDB.DocumentClient({ | |
region: "us-east-1" | |
}) | |
## Get All Items / Scan in DynamoDB | |
dynamoDB | |
.scan({ | |
TableName: "my-table", | |
}) | |
.promise() | |
.then(data => console.log(data.Items)) | |
.catch(console.error) | |
## Get Item | |
dynamoDB | |
.get({ | |
TableName: "my-table", | |
Key: { | |
id: "123", // id is the Partition Key, '123' is the value of it | |
}, | |
}) | |
.promise() | |
.then(data => console.log(data.Item)) | |
.catch(console.error) | |
## Put Item aka Write/Create | |
dynamoDB | |
.put({ | |
Item: { | |
id: "12346", | |
name: "John Doe", | |
email: "[email protected]", | |
}, | |
TableName: "my-table", | |
}) | |
.promise() | |
.then(data => console.log(data.Attributes)) | |
.catch(console.error) | |
## Query for a Set of Items | |
dynamoDB | |
.query({ | |
TableName: 'my-table', | |
KeyConditionExpression: 'id = :hashKey and date > :rangeKey' | |
ExpressionAttributeValues: { | |
':hashKey': '123', | |
':rangeKey': 20150101 | |
} | |
}) | |
.promise() | |
.then(data => console.log(data.Items)) | |
.catch(console.error); | |
## Query (and Scan) DynamoDB Pagination | |
const getAll = async () => { | |
let result, accumulated, ExclusiveStartKey; | |
do { | |
result = await DynamoDB.query({ | |
TableName: argv.table, | |
ExclusiveStartKey, | |
Limit: 100, | |
KeyConditionExpression: 'id = :hashKey and date > :rangeKey' | |
ExpressionAttributeValues: { | |
':hashKey': '123', | |
':rangeKey': 20150101 | |
}, | |
}).promise(); | |
ExclusiveStartKey = result.LastEvaluatedKey; | |
accumulated = [...accumulated, ...result.Items]; | |
} while (result.Items.length || result.LastEvaluatedKey); | |
return accumulated; | |
}; | |
getAll() | |
.then(console.log) | |
.catch(console.error); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment