This guide introduces how to use AWS Lambda to retrieve data from DynamoDB. The data acquisition flow is as follows: API Gateway → Lambda → DynamoDB. This example focuses on the Lambda to DynamoDB part, omitting the details of invoking Lambda from the screen.
Here is an example of retrieving data using userId
as a condition.
const { DynamoDBClient } = require('@aws-sdk/client-dynamodb');
const { QueryCommand, DynamoDBDocumentClient } = require('@aws-sdk/lib-dynamodb');
const client = new DynamoDBClient({});
const docClient = DynamoDBDocumentClient.from(client);
exports.handler = async (event) => {
// Log the incoming event for debugging in CloudWatch
console.log(event);
try {
// Retrieve the user ID sent from the screen
const userId = event.queryStringParameters.userId;
const command = new QueryCommand({
TableName: 'YourDynamoDBTableName',
// Specify the condition
KeyConditionExpression: 'userId = :userId',
// Set the value for :userId
ExpressionAttributeValues: {
':userId': userId
}
});
// Fetch the data
const response = await docClient.send(command);
return {
statusCode: 200,
headers: {
'Access-Control-Allow-Origin': '*',
},
body: JSON.stringify(response)
};
} catch (error) {
// Log the error for debugging in CloudWatch
console.log(error);
return {
statusCode: 400,
headers: {
'Access-Control-Allow-Origin': '*',
},
body: error.message
};
}
};
Since Lambda proxy integration is configured in API Gateway, the response must be returned in a specified format to avoid CORS errors.