Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save Siddhant-K-code/7abda2ff9504c3e8b0cd9cb45152dad9 to your computer and use it in GitHub Desktop.
Save Siddhant-K-code/7abda2ff9504c3e8b0cd9cb45152dad9 to your computer and use it in GitHub Desktop.
Node.js: How to Get DynamoDB Data from Lambda

Node.js: How to Get DynamoDB Data from Lambda

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.

Source Code

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
        };
    }
};

Supplement

Since Lambda proxy integration is configured in API Gateway, the response must be returned in a specified format to avoid CORS errors.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment