Skip to content

Instantly share code, notes, and snippets.

@bodhiprice
Last active October 28, 2020 02:18
Show Gist options
  • Save bodhiprice/1f2e4a2bf4aaa6dc86c4bd2f12ccec5d to your computer and use it in GitHub Desktop.
Save bodhiprice/1f2e4a2bf4aaa6dc86c4bd2f12ccec5d to your computer and use it in GitHub Desktop.
Query all items in DynamoDb using async/await
// Assumes using serverless-webpack or Node 14+
// See here for more details: https://stackoverflow.com/a/60896150
import DynamoDB from 'aws-sdk/clients/dynamodb';
const docClient = new DynamoDB.DocumentClient();
export const handler = async () => {
const params = {
TableName: 'table-name',
KeyConditionExpression: 'pKey = :pkey and sKey > :skey',
ExpressionAttributeValues: {
':pkey': 'some value',
':skey': 123456789,
},
};
const getAllItems = async () => {
const getItems = async startKey => {
if (startKey) {
params.ExclusiveStartKey = startKey;
}
return docClient.query(params).promise();
};
let lastEvaluatedKey;
let items = [];
// While lastEvaluatedKey is not undefined, keep querying Dynamo table...
do {
const result = await getItems(lastEvaluatedKey);
items = items.concat(result.Items);
lastEvaluatedKey = result.LastEvaluatedKey;
} while (lastEvaluatedKey);
return items;
};
const allItems = await getAllItems();
// Do some more stuff with returned items...
return 'OK';
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment