javascript/example_code/lambda/lambda-for-browser/README.md
You can create a browser-based application that passes user selections to an AWS Lambda function, and triggers the Lambda function.
This tutorial shows you how to use the AWS SDK for JavaScript V2 API to invoke these AWS services:
Cost to complete: The AWS services included in this document are included in the AWS Free Tier.
Note: Be sure to terminate all of the resources after you have completed this tutorial to ensure that you are not charged.
To build this cross-service example, you need the following:
You can create the AWS resources required for this cross-service example the AWS Management Console
{
"Version": "2012-10-17",
"Statement": [
{
"Action": "dynamodb:PutItem",
"Resource": "*",
"Effect": "Allow"
},
{
"Action": "lambda:InvokeFunction",
"Resource": "*",
"Effect": "Allow"
},
{
"Effect": "Allow",
"Action": "iam:PassRole",
"Resource": "*",
"Condition": {
"StringEquals": {
"iam:PassedToService": "lambda.amazonaws.com"
}
}
}
]
}
You should update your IAM role's trust policy.
{
"Version": "2012-10-17",
"Statement": [
{
"Effect": "Allow",
"Principal": {
"Federated": "cognito-identity.amazonaws.com"
},
"Action": "sts:AssumeRoleWithWebIdentity",
"Condition": {
"StringEquals": {
"cognito-identity.amazonaws.com:aud": "IDENTITY_POOL_ID"
},
"ForAnyValue:StringLike": {
"cognito-identity.amazonaws.com:amr": "unauthenticated"
}
}
},
{
"Effect": "Allow",
"Principal": {
"Service": "lambda.amazonaws.com"
},
"Action": "sts:AssumeRole"
},
{
"Effect": "Allow",
"Principal": {
"AWS": "USER_ARN"
},
"Action": "sts:AssumeRole"
}
]
}
Create an Amazon DynamoDB table called 'DesignRequests', with the following attributes:
For more information, see Creating a table and Load sample data.
Clone the AWS Code Samples repo to your local environment. See the Github documentation for instructions.
Run the following commands in sequence in the AWS CLI command line to install the AWS service client modules and third-party modules listed in the package.json:
npm install node -g
cd javascript/example_code/lambda/lambda-for-browser
npm install
This app runs from the browser, so we create the interface using HTML and CSS. The app uses JavaScript to provide basic interactive features, and Node.js to invoke the AWS Services.
In index.html, the head section loads the main.js, which contains the following JavaScript and Node.js functions used in the app.
Note: main.js is a bundled file containing all the required JavaScript. You'll create this later in the tutorial.
The remaining code defines the interface features, including a table and buttons.
<!DOCTYPE html>
<head>
<script src="https://sdk.amazonaws.com/js/aws-sdk-2.1044.0.min.js"></script>
<script type="text/javascript" src="main.js"></script>
</head>
<body>
<!--<form action="/myform" method="GET"> -->
<form action="#">
<div align="Center">
<label for="skill"><b>Choose a colour and pattern</b></label>
<select name="colours" id="c1">
<option value="red">Red</option>
<option value="orange">Orange</option>
<option value="yellow">Yellow</option>
<option value="green">Green</option>
<option value="blue">Blue</option>
<option value="indigo">Indigo</option>
<option value="violet">Violet</option>
</select>
<select name="pattern" id="p1">
<option value="floral">Floral</option>
<option value="floral">Floral</option>
<option value="modern">Modern</option>
<option value="paisley">Paisley</option>
<option value="plain">Plain</option>
<option value="plush">Plush</option>
<option value="squares">Squares</option>
<option value="stripes">Stripes</option>
</select>
</form>
<button type="button" onclick="myFunction();">Submit</button>
</body>
</html>
There are two JavaScript scripts
index.js is the AWS Lambda function. It uses the Amazon DynamoDB Document client to pass the user's browser selections to a DynamoDB table.
'use strict'
console.log('Loading function');
var AWS = require('aws-sdk');
// Initialize the Amazon Cognito credentials provider.
AWS.config.region = "REGION";
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: "IDENTITY_POOL_ID",
});
// Create client.
const docClient = new AWS.DynamoDB.DocumentClient();
exports.handler = async(event, context, callback) => {
const params = {
Item: {
Id: event.Item.Id,
Color: event.Item.Color,
Pattern: event.Item.Pattern
},
TableName: event.TableName
};
await docClient.put(params, async function (err, data) {
if (err) {
console.error(
"Unable to add item. Error JSON:",
JSON.stringify(err, null, 2)
);
} else {
console.log("Adding data to dynamodb...");
console.log("Added item:", JSON.stringify(data, null, 2));
}
});
callback(null, event);
};
You compress index.js into a ZIP file. Then create a Lambda function using this ZIP file as follows:
Your Lambda function is displayed.
main.js contains the JavaScript function that invokes the Lambda function. It is triggered when the user clicks the button on the UI of the app.
AWS.config.region = "REGION";
AWS.config.credentials = new AWS.CognitoIdentityCredentials({
IdentityPoolId: "IDENTITY_POOL_ID",
});
// Create client.
const lambda = new AWS.Lambda();
const myFunction = async () => {
const color = document.getElementById("c1").value
const pattern = document.getElementById("p1").value
const id = Math.floor(Math.random() * (10000 - 1 + 1)) + 1;
const params = {
FunctionName: 'forPathryusah', /* required */
Payload: JSON.stringify( { Item: {
Id: id,
Color: color,
Pattern: pattern
},
TableName: "DesignRequests",
})
};
lambda.invoke(params, function (err, data){
if (err) console.log(err, err.stack); // an error occurred
else console.log('Success, payload', data); // successful response
})
};
Open the index.html in your favorite browser, and follow the onscreen instructions.
Congratulations! You have created and deployed the AWS Lambda Browser application. For more AWS multiservice examples, see cross-services.