Last active
October 28, 2020 02:18
-
-
Save bodhiprice/1f2e4a2bf4aaa6dc86c4bd2f12ccec5d to your computer and use it in GitHub Desktop.
Query all items in DynamoDb using async/await
This file contains 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
// 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