Last active
June 1, 2021 15:09
-
-
Save thadeu/d8d381e24609fc7e86317c7c253b63a5 to your computer and use it in GitHub Desktop.
DynamoDB Recursive Query
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
const result = await RecursiveQuery.findByPk({ | |
pk: 'YOUR_PK', | |
keys: "number_primary, status", | |
}); | |
// -> [{ number_primary: '1', status: 'active' }] |
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
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