Skip to content

Instantly share code, notes, and snippets.

@thadeu
Last active June 1, 2021 15:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thadeu/d8d381e24609fc7e86317c7c253b63a5 to your computer and use it in GitHub Desktop.
Save thadeu/d8d381e24609fc7e86317c7c253b63a5 to your computer and use it in GitHub Desktop.
DynamoDB Recursive Query
const result = await RecursiveQuery.findByPk({
pk: 'YOUR_PK',
keys: "number_primary, status",
});
// -> [{ number_primary: '1', status: 'active' }]
class RecursiveQuery {
static async findByPk(props) {
const { pk, evaluatedKey = null, data = [], keys = null } = props;
const queryProps = {
IndexName: "GSI_INDEX_NAME",
KeyConditionExpression: "pk = :pk",
ExpressionAttributeValues: { ":pk": pk },
ExclusiveStartKey: evaluatedKey,
};
if (keys) {
queryProps["ProjectionExpression"] = keys;
}
const result = await client.query(queryProps);
const { LastEvaluatedKey, Items } = result;
// update cache
data.push(Items);
if (LastEvaluatedKey) {
props["evaluatedKey"] = LastEvaluatedKey;
props["data"] = data;
return await this.findByPk(props);
}
// concat arrays
const items = data.reduce((a, b) => a.concat(b), [])
console.info(`RecursiveQuery.byPk found is ${items.length} items`);
return items
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment