0

I am trying to update an existing DynamoDB table record that contains an ID of 0c876d54-195a-46d1-954c-80477e78e70e and set the status column from true to false. I'm using a Lambda function with Node.js to perform the update. The function returns null and there seems to be little documentation to performs what should be such a simple task. Here is what I have tried:

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient({ region: 'us-east-1' });
exports.handler = async(event, context, callback) => {
    await updateTable().then(() => {
        callback(null, {
            statusCode: 201,
            body: '',
            headers: {
                'Access-Control-Allow-Origin': '*'
            }
        });
    }).catch((err) => {
        console.error(err)
    })
};

function updateTable() {
    const params = {
        TableName: "MyTable",
            Key: {
        "ID": "0c876d54-195a-46d1-954c-80477e78e70e"
    },
        UpdateExpression: "SET status = :status",
        ExpressionAttributeValues: {
            ":status": "FALSE"
        }
    }
    return ddb.update(params).promise();
}

1 Answer 1

1

Don't use the .then().catch() and callback pattern when using async. When you are using async Lambda will exit as soon as the code path is done, which will be before you hit the .then().

const AWS = require('aws-sdk');
const ddb = new AWS.DynamoDB.DocumentClient({ region: 'us-east-1' });
exports.handler = async(event, context) => {
    try {
        await updateTable();

        return {
            statusCode: 201,
            body: '',
            headers: {
                'Access-Control-Allow-Origin': '*'
            }
        }
    }
    catch (err) {
        console.error(err);
    }
};

function updateTable() {
    const params = {
        TableName: "MyTable",
            Key: {
        "ID": "0c876d54-195a-46d1-954c-80477e78e70e"
    },
        UpdateExpression: "SET status = :status", //status is a reserved ATTRIBUTE
        ExpressionAttributeValues: {
            ":status": "FALSE"
        }
    }
    return ddb.update(params).promise();
}
Sign up to request clarification or add additional context in comments.

1 Comment

This works. I did fix a syntax issue with the try, catch block and status is a reserved ATTRIBUTE.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.