Search code examples
amazon-web-servicesaws-lambdaaws-amplify

AWS SDK function is not being called when run used on a lambda function deployed by Amplify


I'm trying to add a user to a group in my Amplify project programatically. I created a lambda function as shown below and deployed it using amplify functions. I setup the permissions to the functions's role following this article: https://www.linkedin.com/pulse/aws-amplify-adding-user-group-programmatically-guillermo-misa-iii. The function get's executed. No errors. It doesn't even run the console log which means the callback is not being called. The user is not being added to the group either. There's no error logs in the lambda function logs. Any idea what's happening?

const AWS = require('aws-sdk');

exports.handler = async (event, context, callback) => {
    const cognitoIdentityServiceProvider = new AWS.CognitoIdentityServiceProvider();

    cognitoIdentityServiceProvider.adminAddUserToGroup({
        GroupName: 'abcd', //your confirmed user gets added to this group
        UserPoolId: event.arguments.userPoolId,
        Username: event.arguments.userName
    }, function(err, data) {
        console.log('Ran the function')

        if (err) {
            callback(err) // uh oh, an error
        }

        callback(null, event); // yay! success
    })

    // return response;
};

Solution

  • In the guide I followed, they have used a normal function as the lambda handler:

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

    But I have used an async function:

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

    It seems in an async function, lambda does not wait till the callback is called. It expects us to use the async await syntax in our code. So, I have to convert the function like this:

    try {
        await cognitoIdentityServiceProvider.adminAddUserToGroup({
            GroupName: 'abcd', //your confirmed user gets added to this group
            UserPoolId: event.arguments.userPoolId,
            Username: event.arguments.userName
        }).promise()
    
        callback(null, event); // yay! success
    } catch (error) {
        console.log(error)
    }
    

    Now everything works! Notice that we can get a promise out of aws-sdk functions if we call .promise().