Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why isn't Dynamodb.put working in Lambda Function? Returns null. How to debug?

Debugging lambda is frustrating.

I've got a very simple lambda function:

const AWS = require('aws-sdk')

const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'ap-southeast-2'});

exports.handler = async (event, context, callback) => {

    const params = {
        TableName: 'people-dev',
        Item: {
            id: '1',
            name: 'person',
            email: '[email protected]'
        }
    };

    dynamodb.put(params, (err, data) => {
        if(err) {
            callback(err, null)
        } else{
            callback(null, data)
        }

    });

};

The test response is:

Response:
null

Request ID:
"3d7e9329-3843-4760-917d-4b4d4781dbd7"

Function Logs:
START RequestId: 3d7e9329-3843-4760-917d-4b4d4781dbd7 Version: $LATEST
END RequestId: 3d7e9329-3843-4760-917d-4b4d4781dbd7
REPORT RequestId: 3d7e9329-3843-4760-917d-4b4d4781dbd7  Duration: 243.13 ms Billed Duration: 300 ms     Memory Size: 128 MB Max Memory Used: 29 MB  

Nothing is being written to Dynamo. Nothing useful is logged in cloudwatch. Yes, the function has full permissions to DynamoDB.

like image 689
Emmanuel Avatar asked Jan 26 '23 08:01

Emmanuel


1 Answers

Put async back to its place as using callbacks is outdated and much more error prone. Use the built-in promise() methods available on the node.js aws-sdk and just await on these promises. If you want to deal with errors, just surround your code with a try/catch block.

const AWS = require('aws-sdk')

const dynamodb = new AWS.DynamoDB.DocumentClient({region: 'ap-southeast-2'});

exports.handler = async (event) => {

    const params = {
        TableName: 'people-dev',
        Item: {
            id: '1',
            name: 'person',
            email: '[email protected]'
        }
    };

    await dynamodb.put(params).promise()

    return {
        statusCode: 200,
        body: JSON.stringify({message: 'Success'})
    }

};

More on async/await

like image 149
Thales Minussi Avatar answered Jan 29 '23 11:01

Thales Minussi