Sunday, January 29, 2017

Instagram Clone Using AWS service - Setup Lambda to Insert User into DynamoDB

1. Create an execution role that can allow Lambda service to fully access (read and write) DynamoDB.

* Sign in to the Identity and Access Management (IAM) console at https://console.aws.amazon.com/iam/.

* Select "Roles" and then click "Create New Role" to create a new role.
a. In Role Name, use a name that is unique within your AWS account (for example, lambda-dynamodb-execution-role).
b. In Select Role Type, choose AWS Service Roles, and then choose AWS Lambda. This grants the AWS Lambda service permissions to assume the role.
c. In Attach Policy, choose "AmazonDynamoDBFullAccess". This will allow lambda to be able to access DynamoDB fully.

2. Create lambda script below.
var doc = require('dynamodb-doc');

console.log('Loading function: add/update user in Dynamo');

exports.handler = function(event, context, callback) {
    console.log('Received event:', JSON.stringify(event));

    // Check for the event type
    if (event.eventType === 'SyncTrigger') {

        // Check if this user has ever been created before
        if ('name' in event.datasetRecords && 'email' in event.datasetRecords)
        {
            var db = new doc.DynamoDB();
            var tableName = 'Users'
            var user = {
                'id' : event.identityId,
                'name' : event.datasetRecords.name.newValue,
                'email' : event.datasetRecords.email.newValue,
            };

            var params = {
                'TableName' : tableName,
                'Item' : user
            };

            console.log('Inserting user', params);

            db.putItem(params, function(err, data) {
                console.log(err, data);

                if (err) {
                    console.log('User insert failure', err);
                    callback(err);
                } else {
                    console.log('User insert success', data);
                    callback(null, event);
                }
            });
        } else {
            callback(JSON.stringify(event));
        }
    }
};

3. For lambda script, add trigger source as Cognito Sync Trigger, specify Cognito Identify Pool as InstagramClone, and enable Trigger.
References
---------------
1 http://docs.aws.amazon.com/lambda/latest/dg/with-dynamodb-create-execution-role.html

1 comment: