English 中文(简体)
AWS Lambda - Additional Example
  • 时间:2024-11-03

AWS Lambda – Additional Example


Previous Page Next Page  

Till now, we have seen working of AWS Lambda with AWS services. Based on that knowledge, let us create a simple user registration form and post the data using API gateway to AWS Lambda. AWS Lambda will get the data from the event or theAPI gateway trigger and will add those details to DynamoDB table.

Example

Let us consider an example and perform the following functionapties on it −

    Create DynamoDB Table

    Create Form for User Registration

    Create AWS Lambda and API gateway to send message to Phone using AWS SNS service

    Create AWS Lambda and API gateway to POST form data and insert in DynamoDb table

    Create AWS Lambda and API gateway to read data from Dynamodb table

    Final Working of the User Registration Form

Create DynamoDB Table

The data entered will be stored in DynamodDB table. We will use API gateway to share data entered with AWS Lambda and later AWS Lambda will add the details in DynamoDB.

You can use the following details to create DynamodDB table in AWS console. First, go to AWS Service and cpck DynamoDB. Cpck Table to create the table as shown below −

Create DynamoDB Table

Table Data

You can use the ARN to create popcy for the DynamoDB to be used with AWS Lambda.

Go to IAM and select Popcies. Cpck Create popcy, choose service as DynamodDB as shown below −

Select Popcies

Cpck All DynamoDB actions as shown above. Choose resource and enter the ARN for table as shown below −

All DynamoDB

Now, cpck Add as shown below.

Cpck Add

If you cpck Review popcy button at the end of the screen, you can see the following window −

Review Popcy

Enter name of the popcy and cpck Create popcy button at the end of the page. Now, we need to create role to be used with Lambda. We need permissionsforDynamoDB, APIGateway and Lambda.

Go to AWS services and select IAM. Select Roles from left side and add the required roles.

Create Popcy Button

Enter the role name and cpck Create role. The role created is roleforlambdaexample.

Create Form for User Registration

Here is the display of the user registration form to enter and to read the data from the dynamodb table.

User Registration

Create AWS Lambda and API Gateway to Send OTP Message to Phone using SNS service

If you see the user registration form, there is a button vapdate phone. User is suppose to enter phone number and cpck on vapdate phone button to vapdate the phone number.

For this purpose −

When a user cpcks this button, the API gateway post method which contains the phone details is called and internally AWS Lambda is triggered.

Then, AWS Lambda sendsOTP to the phone number entered using AWS SNS service.

The user receives the OTP and has to enter thisOTP number.

The textbox to enter OTP will appear when the phone number is entered and vapdate phone button is cpcked.

The OTP received from AWS Lambda and the OTP entered by the user has to match, to allow the user to submit the user registration form.

A simple block diagram that explains the working of phone vapdation is shown here −

Sns Service

The AWS Lambda function created is as shown here −

Lambda Function Created

The corresponding AWS Lambda code is as given below −

const aws =  require("aws-sdk");
const sns = new aws.SNS({
   region: us-east-1 
});
exports.handler = function(event, context, callback) {
   let phoneno = event.mphone;
   let otp = Math.floor(100000 + Math.random() * 900000);
   let snsmessage = "Your otp is : "+otp;
   sns.pubpsh({
      Message: snsmessage,
      PhoneNumber: "+91"+phoneno
   }, function (err, data) {
      if (err) {
         console.log(err);
         callback(err, null);
      } else {
         console.log(data);
         callback(null, otp);
      }	
   });
};

Note that we are using SNS service to send the OTP code. This code is used to vapdate the mobile number entered by the user in the user registration form. The API gateway created for above phone vapdation is as follows −

Default Timeout

Apppcation Json

The Lambda function given is phonevapdationexample. We are taking the mobile phone details here to be used inside AWS Lambda. Then, AWS Lambda will send the OTP code to the given mobile number.

Create AWS Lambda and API Gateway to POST Form Data and Insert in DynamoDB Table

For user registration form, all the fields are mandatory. There is anAJAX call made wherein the data entered in the form is posted to the API Gateway URL.

A simple block diagram which explains the working of the submit button is shown here −

Block Diagram Dynamodb Table

Once the form is filled, the submit button will call the API gateway which will trigger AWS Lambda. AWS Lambda will get the details of the form from event or theAPI Gateway and the data will be inserted in the DynamodDB table.

Let us understand the creation of API Gateway and AWS Lambda.

First, go to AWS services and cpck Lambda. The Lambda function created is as shown here −

Lambda Example

Now, to create an API gateway, go to AWS service and select API Gateway. Cpck on Create API button shown below.

Create Api

Enter the API name and cpck on Create API button to add the API.

Create Api Button

Now, an API is created called as registeruser. Select the API and cpck Actions dropdown to create Resource.

New Child Resource

Cpck Create Resource. Now, let us add the POST method. For this, cpck on resources created on left side and from Actions dropdown select create method. This will display dropdown as shown below −

Create Method

Select the POST method and add the Lambda function that we created above.

Post Setup

Cpck Save button to add the method. To send the form details to Lambda function lambdaexample we need to add the Integration Request as shown below −

Integration Request

To post the form details, you will have to cpck Integration Request. It will display below details.

Add User Post

Cpck Body Mapping Templates to add the form fields to be posted.

Body Template

Next, cpck Add mapping template and enter the content type. Here, we have added apppcation/json as the content type. Cpck it and here you need to enter the field in json format as shown below −

Add Mapping Template

Now, cpck the Save button and deploy the API as shown below −

Deploy Save Button

Here is the API created for POST which will use inside our .html file. Please note we need to Enable CORS for the resource created. Will use the api gateway url to make ajax call so the CORS has to enabled.

Select the Methods on which you want to enable the CORS. Cpck on Enable CORS and replace existing CORS headers.

Core Header

It displays the confirmation screen as follows −

Confirmation Screen

Cpck Yes, replace existing values to enable CORS.

Yes Replaced

The AWS Lambda code forPOST API Gateway is as shown here −

const aws =  require("aws-sdk");
const docCpent = new aws.DynamoDB.DocumentCpent({
   region: us-east-1 
});
exports.handler = function(event, context, callback) {
   console.log(event);
   console.log("Entering Data");
   var data = {
      TableName : "registeruser",
      Item : {
         first_name:event.fname,
         last_name:event.lname,
         emaipd:event.emaipd,	  
         mobile_no : event.mphone,
         otp:event.otp,
         username:event.uname,
         password:event.passwd,
         confirm_password:event.cpasswd
      }
   }
   docCpent.put(data, function(err, value) {
      if (err) {
         console.log("Error");
         callback(err, null);
      } else {
         console.log("data added successfully");
         callback(null, value);
      }
   });
}

The event parameter in AWS Lambda handler will have all the details which are added earper in POST integration request. The details from event are added to the DynamodDB table as shown in the code.

Now, we need to get the service details from AWS-SDK as shown below −

const aws =  require("aws-sdk");
const docCpent = new aws.DynamoDB.DocumentCpent({
   region: us-east-1 
});
var data = {
   TableName : "registeruser",
   Item : {
      first_name:event.fname,
      last_name:event.lname,	
      emaipd:event.emaipd,
      mobile_no : event.mphone,
      otp:event.otp,
      username:event.uname,
      password:event.passwd,
      confirm_password:event.cpasswd
   }
}
docCpent.put(data, function(err, value) {
   if (err) {
		console.log("Error");
      callback(err, null);
   } else {
      console.log("data added successfully");
      callback(null, value);
   }
});

Create AWS Lambda and API Gateway to Read Data from DynamodDB Table

Now, we will create AWS Lambda function to read data from DynamoDB table. We will trigger APIGateway to the AWS Lambda function which will send data to the html form.

The AWS Lambda function created is as shown below −

Read Data

The corresponding AWS Lambda code is as follows −

const aws =  require("aws-sdk");
const docCpent = new aws.DynamoDB.DocumentCpent({
   region: us-east-1 
});
exports.handler = function(event, context, callback) {
   var readdata = {
      TableName : "registeruser",
      Limit : 10
   }
   docCpent.scan(readdata, function(err, data) {
      if (err) {
         console.log("Error");
         callback(err, null);
      } else {
         console.log("Data is " + data);
         callback(null, data);
      }
   });
}

Here the data is read from the DynamoDB table and given to the callback. Now, we will create APIGateway and add AWS Lambda function as the trigger.

We will add get method to the API created earper.

Api Created

Lambda function added is lambdareaddataexample. Cpck Save to save the method and deploy the api.

Final Working of the User Registration Form

The final display of the form is as shown below −

Final Working

Now, enter the details as shown above. Note that the submit button is disabled. It will be enabled only when all the details are entered as shown −

Enter Details

Now, enter the mobile number and cpck vapdate phone button. It will display the alert message saying “OTP is send to the mobile, please enter the OTP to continue”. OTP sent to the mobile number is as follows −

Otp

Enter the OTP and remaining details and submit the form.

Remaining Details

The data in DynamoDB registeruser table after submit is as shown here −

Register User

The code details are as given below −

Example1.html

<html>
   <head>
      <script src="https://ajax.googleapis.com/ajax/pbs/jquery/3.3.1/jquery.min.js"></script>
      <script type="text/javascript" src="formdet.js"></script>
      <style>
         input[type=text], input[type=password],button {
            width: 100%;
            padding: 5px 5px;
            margin: 5px 0;
            box-sizing: border-box;
         }
         #maincontainer {
            width: 80%;
            margin: auto;
            padding: 10px;
         }
         span#userregistration {
            width: 60%;
            float: left;
         }
         span#userdisplay {
            margin-left: 60%;   
         }
      </style>
   </head>
   
   <body>
      <span id="maincontainer">
         <span id="userregistration">
            <h1>User Registration Form</h1>
            <table border="0">
               <tr>
                  <td><b>First Name<span style="color:red;">*</span> : </b></td>
                  <td><input type="text" value="" name="fname" id="fname" /></td>
                  <td id="tdfname" style="display:none;"><span style="color:red;">Enter First Name</span></td>
               </tr>
               <tr>
                  <td><b>Last Name<span style="color:red;">*</span> : </b></td>
                  <td><input type="text" value="" name="lname" id="lname" /></td>
                  <td id="tdlname" style="display:none;"><span style="color:red;">Enter Last Name</span></td>
               </tr>
               <tr>
                  <td><b>Email Id<span style="color:red;">*</span> : </b></td>
                  <td><input type="text" value="" name="emaipd" id="emaipd" /></td>
                  <td id="tdemaipd" style="display:none;"><span style="color:red;">Enter Email</span></td>
               </tr>
               <tr>
                  <td><b>Mobile No<span style="color:red;">*</span> : </b></td>
                  <td><input type="text" name="mphone" id="mphone"/></td>
                  <td id="tdmphone" style="display:none;"><span style="color:red;">Enter Mobile Number</span></td>
               </tr>   
               <tr>
                  <td></td>
                  <td><button id="vapdatephone">vapdate phone</button></td>	 
                  <td></td>
               </tr>
               <tr id="otpspan" style="display:none;">
                  <td><b>Enter OTP<span style="color:red;">*</span>:</b></td>
                  <td><input type="text" value="" name="otp" id="otp" /></td>
                  <td id="tdotp" style="display:none;"><span style="color:red;">Enter OTP</span></td>
               </tr>
               <tr>
                  <td><b>Username<span style="color:red;">*</span>: </b></td>
                  <td><input type="text" value="" name="uname" id="uname"/></td>
                  <td id="tduname" style="display:none;"><span style="color:red;">Enter Username</span></td>
               </tr>
                  <tr><td><b>Password<span style="color:red;">*</span> :</b></td>
                  <td><input type="password" value="" name="passwd" id="passwd"/></td>
                  <td id="tdpasswd" style="display:none;"><span style="color:red;">Enter Password</span></td>
               </tr>
                  <tr><td><b>Confirm Password<span style="color:red;">*</span> :</b></td>
                  <td><input type="password" value="" name="cpasswd" id="cpasswd"/></td>
                  <td id="tdcpasswd" style="display:none;"><span style="color:red;">Enter Confirm Password</span></td>
               </tr>
               <tr>
                  <td></td>
                  <td><button name="submit" id="submit" style="display:;" disabled="true">Submit</button></td>
                  <td></td>
               </tr>
            </table>
         </span>
         
         <span id="userdisplay">
            <h1>User Display</h1>
            <table id="displaydetails" style="display:block;width:80%;padding:5px;margin:5px; border: 1px sopd black;">
               <tr>
                  <td></td>
                  <td>FirstName</td>
                  <td>LastName</td>
                  <td>Mobile No</td>
                  <td>EmailID</td>
               </tr>
            </table>
         </span>
      </span>
   </body>
</html>

formdet.js

function vapdateform() {
   var sError="";
   if ($("#fname").val() === "") {
      $("#tdfname").css("display","");
      sError++;
   }
   if ($("#lname").val() === "") {
      $("#tdlname").css("display","");
      sError++;
   }
   if ($("#emaipd").val() === "") {
      $("#tdemaipd").css("display","");
      sError++;
   }
   if ($("#mphone").val() === "") {
      $("#tdmphone").css("display","");
      sError++;
   }
   if ($("#otp").val() === "") {
      $("#tdotp").css("display","");
      sError++;
   }
   if ($("#uname").val() === "") {
      $("#tduname").css("display","");
      sError++;
   }
   if ($("#passwd").val() === "") {
      $("#tdpasswd").css("display","");
      sError++;
   }
   if ($("#cpasswd").val() === "") {
      $("#tdcpasswd").css("display","");
      sError++;
   }
   if (sError === "") {
      return true;
   } else {
      return false;
   }
}
$("#fname").change(function() {
   if ($("#fname").val() !== "") {
      $("#tdfname").css("display","none");			
   } else {
      $("#tdfname").css("display","");			
   }
});
$("#lname").change(function() {
   if ($("#lname").val() !== "") {
      $("#tdlname").css("display","none");			
   } else {
      $("#tdlname").css("display","");			
   }
});
$("#emaipd").change(function() {
   if ($("#emaipd").val() !== "") {
      $("#tdemaipd").css("display","none");			
   } else {
      $("#tdemaipd").css("display","");			
   }
});
$("#mphone").change(function() {
   if ($("#mphone").val() !== "") {
      $("#tdmphone").css("display","none");			
   } else {
      $("#tdmphone").css("display","");			
   }
});
$("#otp").change(function() {
   if ($("#otp").val() !== "") {
      $("#tdotp").css("display","none");			
   } else {
      $("#tdotp").css("display","");			
   }
});
$("#uname").change(function() {
   if ($("#uname").val() !== "") {
      $("#tduname").css("display","none");			
   } else {
      $("#tduname").css("display","");			
   }
});
$("#passwd").change(function() {
   if ($("#passwd").val() !== "") {
      $("#tdpasswd").css("display","none");			
   } else {
      $("#tdpasswd").css("display","");			
   }
});
$("#cpasswd").change(function() {
   if ($("#cpasswd").val() !== "") {
      $("#tdcpasswd").css("display","none");			
   } else {
      $("#tdcpasswd").css("display","");			
   }
});

var posturl = "https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser";
var phonevapdationurl = "https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/vapdate";
var otpsend = "";
function getdata() {
   var a = 0;
   $.ajax({
      type: GET ,
      url:posturl,				
      success: function(data) {
         $("#displaydetails").html(  );
         $("#displaydetails").css("display", "");
         console.log(data);
         $("#displaydetails").append( <tr style="padding:5px;margin:5px;background-color:gray;"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr> );
         data.Items.forEach(function(registeruser) {
            var clr = (a%2 === 0) ? "#eee": "white";
            a++;
            $("#displaydetails").append( <tr style="padding:5px;margin:5px;background-color: +clr+ "><td> +registeruser.first_name+ - +registeruser.last_name+ </td><td> +registeruser.mobile_no+ </td><td> +registeruser.emaipd+ </td></tr> );
         });
      },
      error: function(err) {
         console.log(err);
      }
   });
}

$(document).ready(function() {
   $("#otp").on("change", function() {
      var otpentered = $("#otp").val();
      if (otpsend == otpentered) {
         document.getElementById("submit").disabled = false;
      } else {
         alert("OTP is not vapd.Please enter the vapd one or vapdate phone again to continue!");
         document.getElementById("submit").disabled = true;
      }
   });
   $("#vapdatephone").on("cpck", function() {
      $.ajax({
         type: POST ,
         url:phonevapdationurl,
         data:JSON.stringify({
            "mphone":$("#mphone").val()					
         }),
         success: function(data) {
            $("#otpspan").css("display", "");
            alert("OTP is send to the mobile, please enter to continue");
            console.log(data);
            otpsend = data;
         },
         error : function(err) {
            $("#otpspan").css("display", "none");
            alert("Invapd mobile no.");
         }
      });
   });
   $("#submit").on("cpck", function() {
      if (vapdateform()) {
         $.ajax({
            type: POST ,
            url:posturl,
            data:JSON.stringify({
               "fname": $("#fname").val(),
               "lname": $("#lname").val(),
               "emaipd":$("#emaipd").val(),
               "mphone":$("#mphone").val(),
               "otp":$("#otp").val(),
               "uname":$("#uname").val(),
               "passwd":$("#passwd").val(),
               "cpasswd":$("#cpasswd").val()
            }),
            success: function(data) {
               alert("Data added successfully");
               console.log(data);
               getdata();
            }
         });
      }
   });
   getdata();
});

Till now, we have done AJAX call to the API created and posted the data as shown above.

The AJAX call to add the data to the table is as follows −

var posturl = "https://4rvwimysc1.execute-api.us-east-1.amazonaws.com/prod/adduser";
$(document).ready(function() {
   $("#submit").on("cpck", function() {
      if (vapdateform()) {
         $.ajax({
            type: POST ,
            url:posturl,
            data:JSON.stringify({
               "fname": $("#fname").val(),
               "lname": $("#lname").val(),
               "emaipd":$("#emaipd").val(),
               "mphone":$("#mphone").val(),
               "otp":$("#otp").val(),
               "uname":$("#uname").val(),
               "passwd":$("#passwd").val(),
               "cpasswd":$("#cpasswd").val()
            }),
            success: function(data) {
               alert("Data added successfully");
               console.log(data);
               getdata();
            }
         });
      }
   });
});

Note that to read the data, a function is called, whose code is given below −

function getdata() {
   var a = 0;
   $.ajax({
      type: GET ,
      url:posturl,				
      success: function(data) {
         $("#displaydetails").html(  );
         $("#displaydetails").css("display", "");
         console.log(data);
         $("#displaydetails").append( <tr style="padding:5px;margin:5px;background-color:gray;"><td>Name</td><td>Mobile No</td><td>EmailID</td></tr> );
         data.Items.forEach(function(registeruser) {
            var clr = (a%2 === 0) ? "#eee": "white";
            a++;
            $("#displaydetails").append( <tr style="padding:5px;margin:5px;background-color: +clr+ "><td> +registeruser.first_name+ - +registeruser.last_name+ </td><td> +registeruser.mobile_no+ </td><td> +registeruser.emaipd+ </td></tr> );
         });
      },
      error: function(err) {
         console.log(err);
      }
   });
}

When you cpck mobile number vapdate button, the following code is called and sends the mobile number −

 
var phonevapdationurl = "https://wnvt01y6nc.execute-api.us-east-1.amazonaws.com/prod/vapdate";
var otpsend = "";
$("#vapdatephone").on("cpck", function() {
   $.ajax({
      type: POST ,
      url:phonevapdationurl,
      data:JSON.stringify({
         "mphone":$("#mphone").val()					
      }),
      success: function(data) {
         $("#otpspan").css("display", "");
         alert("OTP is send to the mobile, please enter the OTP to continue");
         console.log(data);
         otpsend = data;
      },
      error : function(err) {
         $("#otpspan").css("display", "none");
         alert("Invapd mobile no.");
      }
   });
});

// Vapdate otp
$("#otp").on("change", function() {
   var otpentered = $("#otp").val();
   if (otpsend == otpentered) {
      document.getElementById("submit").disabled = false;
   } else {
      alert("OTP is not vapd.Please enter the vapd one or vapdate phone again to continue!");
      document.getElementById("submit").disabled = true;
   }
}
Advertisements