Reputation: 1269
I have a lambda function written in node, and I am trying to get data for a particular workout session.
The url looks something like this
workout/{workoutId}/sessions/{sessionId}
I know I can do something like the following if I just wanted to the workoutId
module.exports.getWorkoutSession = (event, context, callback) => {
const { workoutId } = event.pathParameters;
const params = {
TableName: workoutTable,
Key: {
id: workoutId,
},
};
return db.get(params).promise().then(res => {
if(res.item) {callback(null, response(200, res.Item));} else {
callback(null, response(404, {error: "workoutId not found"}))
}
})
};
but how can I modify this function so I can get the sessionData for a particular workout?
Upvotes: 0
Views: 1346
Reputation: 2096
The answer depends on how the data is stored in Dynamo DB. If you have these two use cases -
Then these two can be solved by having the following table structure
Hash Key: workoutId
Range Key(Partition Key): sessionId
and the following code
/** API to get all sessions of a workout. Called by url workout/{workoutId} */
module.exports.getWorkoutSessions = async (event, context, callback) => {
const { workoutId } = event.pathParameters;
const params = {
TableName: workoutTable,
KeyConditionExpression: '#workoutId = :workoutId',
ExpressionAttributeNames: {
'#workoutId': 'workoutId'
},
ExpressionAttributeValues: {
':workoutId': workoutId
}
};
const db = new AWS.DynamoDB.DocumentClient();
try {
const res = await db.query(params).promise();
return res.Items;
} catch (error) {
console.error('Error while getting workout sessions', error);
throw error;
}
};
/** API to get a specific session of a workout. Called by url workout/{workoutId}/sessions/{sessionId} */
module.exports.getWorkoutSession = async (event, context, callback) => {
const { workoutId, sessionId } = event.pathParameters;
const params = {
TableName: workoutTable,
Key: {
workoutId: workoutId,
sessionId: sessionId
}
};
const db = new AWS.DynamoDB.DocumentClient();
try {
return await db.getItem(params).promise();
} catch (error) {
console.error('Error while getting workout session', error);
throw error;
}
};
Upvotes: 2