Skip to content

Commit

Permalink
Implemented DynamoDB built-in pagination consideration to get all tra…
Browse files Browse the repository at this point in the history
…inspace endpoint
  • Loading branch information
alantao912 committed Sep 22, 2023
1 parent b2b03b8 commit 0cf2940
Showing 1 changed file with 22 additions and 14 deletions.
36 changes: 22 additions & 14 deletions serverless/packages/functions/src/trainspace/get_all_trainspace.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,21 +11,29 @@ export const handler: APIGatewayProxyHandlerV2 = async (event) => {

const client: DynamoDBClient = new DynamoDBClient({});
const docClient: DynamoDBDocumentClient = DynamoDBDocumentClient.from(client);

const getCommand = new QueryCommand({
TableName: "trainspace",
IndexName: "uid",
KeyConditionExpression: "uid = :uid",
ExpressionAttributeValues: {
":uid" :
{
S: user_id
}
}
});
const fetchedTrainspaceIds: Array<string> = [];
let lastEvaluatedKey = undefined;

const results = await docClient.send(getCommand);
const fetchedTrainspaceIds = results['Items']?.map(trainspace => trainspace['trainspace_id'].S);
do {
const getCommand = new QueryCommand({
TableName: "trainspace",
IndexName: "uid",
KeyConditionExpression: "uid = :uid",
ExpressionAttributeValues: {
":uid" :
{
S: user_id
}
},
ExclusiveStartKey: lastEvaluatedKey
});

const results = await docClient.send(getCommand);
lastEvaluatedKey = results.LastEvaluatedKey;
const page: Array<string> = results['Items']?.map(trainspace => trainspace['trainspace_id'].S);
page.forEach(id => fetchedTrainspaceIds.push(id));

} while (lastEvaluatedKey !== undefined);
return {
statusCode: 200,
body: JSON.stringify({ trainspace_ids : fetchedTrainspaceIds})
Expand Down

0 comments on commit 0cf2940

Please sign in to comment.