Use Lambda with Node.js to Insert Data Into DynamoDB

2021/6/13 min read
bookmark this
Responsive image

This blog show how to create AWS Lambda with Node.js and insert record into DynamoDB, also shows manully deploy Lambda as package to AWS from the your local develop environment.   

Prequirement

  • Have an AWS Account
  • Setup AWS Cli Config
  • Create AWS DynamoDB Table
  • Install Node.js on Mac

Create AWS Role for Lambda to Access DynamoDB

Here, we'll create new Lambda policy to access DynamoDB, go to the AWS Roles and click Create role. 

Choose Lambda service and click add permission.

At the attach permissions policies page, click create policy, you can use either the visual editor or JSON view, what we gonna do here, is providing the Lambda to have DynamoDB PutItem permission. Following are code snippet how it shows at the JSON view. As you can see, this policy is allow dynamodb PutItem operation because our code later will use PutItem to add record to DynamoDB. 

{
    "Version": "2012-10-17",
    "Statement": [
        {
            "Sid": "VisualEditor0",
            "Effect": "Allow",
            "Action": "dynamodb:PutItem",
            "Resource": "*"
        }
    ]
}

Create Node.js code for Lambda

Now, we'll back to our local develop environment and write some code. First we'll need to setup the node.js package file, you can run following command to create a default package file. This will create package.json file.

Create package.json file

npm init -y

Create Lambda node.js code

Run this command to open command editor.

nano index.js

At the command editor, paste following code and save the index.js file. This will be the file that we'll deploy Lambda later. 

Following is assume we already have table called S3BucketImages, you can either go to AWS Dynamodb to create the table and make sure the table's region match to your code. Set the Partition key as UniqueKey. 

onst AWS = require('aws-sdk');
const dynamodbClient = new AWS.DynamoDB.DocumentClient();

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

    AWS.config.update({
        region:  "us-west-1",
    });

    let putRequest = {
        TableName: 'S3BucketImages',
        Item: {
            "UniqueKey": new Date().toString()
        }
    };

    await dynamodbClient.put(putRequest).promise()
    .then((data) => {
        console.info('successfully update to dynamodb', data)
    })
    .catch((err) => {
        console.info('failed adding data dynamodb', err)
    });

};

Parepare package to deploy to AWS Lambda

Now, we'll start to prepare deployment file as zip file and will deploy to AWS as AWS Cli command line. The code we have only have dependency for aws-sdk, so let's install it, this will create node_modules on your local folder.

npm install aws-sdk

Run this command at your terminal to include our index.js and node_module and create zip file.

zip -r index.zip index.js node_modules

We'll then run below command to create lambda function,  you'll replace the AWS account id and the role created earlier. 

aws lambda create-function --function-name my-test-lambda \
--zip-file fileb://index.zip --handler index.handler --runtime nodejs12.x \
--timeout 10 --memory-size 1024 \
--role arn:aws:iam::{Your-AWS-Account-ID}:role/{The-AWS-Role-Can-Access-DynamoDB}

Test Lambda function

This should be pretty much everything you need to access DynamoDB from lambda, you can use the Test tab at the lambda, make sure it actually add new record into dynamodb.