How to fetch/scan all items from AWS dynamodb using node.js. I am posting my code here.
var docClient = new aws.DynamoDB.DocumentCl
For those who are NOT USING AWS.DynamoDB.DocumentClient, this solution will work. I have split the functionality into multiple modules for easy readability and using async/await.
const AWS = require("aws-sdk");
AWS.config.update({
// update table region here
region: "us-west-2"
});
var dynamodb = new AWS.DynamoDB();
const performAsynScanOperation = (scanParams) => {
return new Promise((resolve, reject) => {
dynamodb.scan(scanParams, function (err, responseData) {
if (err) {
reject(err)
} else {
resolve(responseData)
}
})
})
}
const getAllRecords = async (tableName) => {
let allItems = [];
let LastEvaluatedKeyFlag = true;
let scanParams = { TableName: tableName }
while (LastEvaluatedKeyFlag) {
let responseData = await performAsynScanOperation(scanParams)
let batchItems = responseData.Items;
allItems = allItems.concat(batchItems);
if (responseData.LastEvaluatedKey) {
LastEvaluatedKeyFlag = true;
console.log('LastEvaluatedKey', responseData.LastEvaluatedKey)
scanParams.ExclusiveStartKey = responseData.LastEvaluatedKey
} else {
LastEvaluatedKeyFlag = false;
}
}
return allItems;
}
getAllRecords('').then((allItems)=>{
console.log(allItems)
})