Bug/AWS

[AWS CDK] {"message": "Internal server error"} >> cannot find modules

brightlightkim 2022. 3. 29. 06:56
root@BYUB-DM-7:/mnt/c/Users/k2289/repos/aws_cdk_project-2/cdk-workshop# curl -i https://e682ok6625.execute-api.us-east-1.amazonaws.com/prod/
HTTP/2 502 
content-type: application/json
content-length: 36
date: Mon, 28 Mar 2022 21:53:12 GMT
x-amzn-requestid: f1adfafe-8b12-4be5-927d-f49d3dc947dd
x-amzn-errortype: InternalServerErrorException
x-amz-apigw-id: PtwrCFj6IAMFdVA=
x-cache: Error from cloudfront
via: 1.1 eb9103174f828a69a975f55ae9d3f4fa.cloudfront.net (CloudFront)
x-amz-cf-pop: LAX3-C2
x-amz-cf-id: 5_U9xgyXwkYu9uwjHkKpBGPNd5IrryogHMb7fTxrmxI-cAia_T5YIQ==

{"message": "Internal server error"}root@BYUB-DM-7:/mnt/c/Users/k2289/repos/aws_cdk_project-2/cdk-workshop#
export class HitCounter extends Construct {

    //* allows accessing the counter function */
    public readonly handler: lambda.Function;
    
    constructor(scope: Construct, id: string, props: HitCounterProps) {
        super(scope, id);

        const table = new dynamodb.Table(this, 'Hits', {
            partitionKey: {name: 'path', type: dynamodb.AttributeType.STRING}
        });

        this.handler = new lambda.Function(this, 'HitCounterHandler', {
            runtime: lambda.Runtime.NODEJS_14_X,
            handler: 'hitcounter.handler',
            code: lambda.Code.fromAsset('lambda'),            
            environment: {
                DOWNSTREAM_FUNCTION_NAME: props.downstream.functionName,
                HITS_TABLE_NAME: table.tableName
            }
        })

        table.grantReadWriteData(this.handler);

        props.downstream.grantInvoke(this.handler);
    }
}

So to check this stuff, I need to get the CloudWatch to find the log

And I found out that it was a simple error of not finding module. I just mistyped require "aws-cdk" I should have typed aws-sdk instead. Finally, it worked now.

const {DynamoDB, Lambda} = require('aws-sdk');

exports.handler = async function(event) {
    console.log("request", JSON.stringify(event, undefined, 2));

    //create AWS SDK Clients
    const dynamo = new DynamoDB();
    const lambda = new Lambda();

    //update dynamo entry for "path" with hits++
    await dynamo.updateItem({
        TableName: process.env.HITS_TABLE_NAME,
        Key: { path: { S: event.path } },
        UpdateExpression: 'ADD hits :incr',
        ExpressionAttributeValues: { ':incr': {N: '1'}}
    }).promise();

    //call downstream function and capture response
    const resp = await lambda.invoke({
        FunctionName: process.env.DOWNSTREAM_FUNCTION_NAME,
        Payload: JSON.stringify(event)
    }).promise();

    console.log('downstream response:', JSON.stringify(resp, undefined, 2));

    return JSON.parse(resp.Payload);
}