The AWS SDK for JavaScript V3 API Reference Guide describes in detail all the API operations for the AWS SDK for JavaScript version 3 (V3).
Build an app to submit data to DynamoDB
This cross-service Node.js tutorial shows how to build an app that enables users to submit data to an Amazon DynamoDB table. This app uses the following services:
AWS Identity and Access Management (IAM) and Amazon Cognito for authorization and permissions.
Amazon DynamoDB (DynamoDB) to create and update the tables.
Amazon Simple Notification Service (Amazon SNS) to notify the app administrator when a user updates the table.
The scenario
In this tutorial, an HTML page provides a browser-based application for submitting data to a Amazon DynamoDB table. The app uses Amazon SNS to notify the app administrator when a user updates the table.
![Relationship among the browser interface, the SDK, and AWS services in the submitting data app.](/images/sdk-for-javascript/v3/developer-guide/images/submitting_data.png)
To build the app:
Prerequisites
Complete the following prerequisite tasks:
-
Set up the project environment to run these Node TypeScript examples, and install the required AWS SDK for JavaScript and third-party modules. Follow the instructions on GitHub
. Create a shared configurations file with your user credentials. For more information about providing a shared credentials file, see Shared config and credentials files in the AWS SDKs and Tools Reference Guide.
Create the AWS resources
This app requires the following resources:
AWS Identity and Access Management (IAM) Unauthenticated Amazon Cognito user role with the following permissions:
sns:Publish
dynamodb:PutItem
A DynamoDB table.
You can create these resources manually in the AWS console, but we recommend provisioning these resources using AWS CloudFormation as described in this tutorial.
Create the AWS resources using AWS CloudFormation
AWS CloudFormation enables you to create and provision AWS infrastructure deployments predictably and repeatedly. For more information about AWS CloudFormation, see the AWS CloudFormation User Guide.
To create the AWS CloudFormation stack using the AWS CLI:
Install and configure the AWS CLI following the instructions in the AWS CLI User Guide.
Create a file named
setup.yaml
in the root directory of your project folder, and copy the content here on GitHubinto it. Note
The AWS CloudFormation template was generated using the AWS CDK available here on GitHub
. For more information about the AWS CDK, see the AWS Cloud Development Kit (AWS CDK) Developer Guide. Run the following command from the command line, replacing
STACK_NAME
with a unique name for the stack, andREGION
in your AWS region.Important
The stack name must be unique within an AWS Region and AWS account. You can specify up to 128 characters, and numbers and hyphens are allowed.
aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM --region REGION
For more information on the
create-stack
command parameters, see the AWS CLI Command Reference guide, and the AWS CloudFormation User Guide.To view the resources created, open AWS CloudFormation in the AWS management console, choose the stack, and select the Resources tab.
When the stack is create, use the AWS SDK for JavaScript to populate the DynamoDB table, as described in Populating the table.
Populating the table
To populate the table, first create a directory named libs
, and in it create
a file named dynamoClient.js
, and paste the content below into it. Replace REGION
with your AWS Region, and replace IDENTITY_POOL_ID
with an Amazon Cognito Identity Pool ID. This creates the DynamoDB client object.
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity"; import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; const REGION = "REGION"; const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID. // Create an Amazon DynaomDB service client object. const dynamoClient = new DynamoDBClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IDENTITY_POOL_ID, }), }); export { dynamoClient };
This code is available
here on GitHub
Next, create a dynamoAppHelperFiles
folder in your project folder, create a file update-table.js
in it, and copy the content
here on GitHub
// Import required AWS SDK clients and commands for Node.js import { PutItemCommand } from "@aws-sdk/client-dynamodb"; import { dynamoClient } from "../libs/dynamoClient.js"; // Set the parameters export const params = { TableName: "Items", Item: { id: { N: "1" }, title: { S: "aTitle" }, name: { S: "aName" }, body: { S: "aBody" }, }, }; export const run = async () => { try { const data = await dynamoClient.send(new PutItemCommand(params)); console.log("success"); console.log(data); } catch (err) { console.error(err); } }; run();
Run the following command from the command line.
node update-table.js
This code is available
here on GitHub
Create a front-end page for the app
Here you create the front-end HTML browser page for the app.
Create a DynamoDBApp
directory, create a file named
index.html
, and copy in code from here on GitHubscript
element adds
the main.js
file, which contains all the required JavaScript
for the example. You will create the main.js
file later in this tutorial.
The remaining code in index.html
creates the browser page that
captures the data that users input.
This example code can be found here on GitHub
Create the browser script
First, create the service client objects required for the example. Create a libs
directory, create snsClient.js
, and
paste the code below into it. Replace REGION
and
IDENTITY_POOL_ID
in each.
Note
Use the ID of the Amazon Cognito identity pool you created in Create the AWS resources .
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity"; import { SNSClient } from "@aws-sdk/client-sns"; const REGION = "REGION"; const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID. // Create an Amazon Comprehend service client object. const snsClient = new SNSClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IDENTITY_POOL_ID, }), }); export { snsClient };
This code is available here on GitHub.
To create the browser script for this example, in a folder named
DynamoDBApp
, create a Node.js module with the file name
add_data.js
and paste the code below into it. The submitData
function submits data to a DynamoDB table,
and sends an SMS text to the app administrator using Amazon SNS.
In the submitData
function, declare variables for the target
phone number, the values entered on the app interface, and for the name of the Amazon S3
bucket. Next, create a parameters object for adding an
item to the table. If none of the values is empty, submitData
adds the item
to the table, and sends the message. Remember to make the function available to the
browser, with window.submitData = submitData
.
// Import required AWS SDK clients and commands for Node.js import { PutItemCommand } from "@aws-sdk/client-dynamodb"; import { PublishCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; import { dynamoClient } from "../libs/dynamoClient.js"; export const submitData = async () => { //Set the parameters // Capture the values entered in each field in the browser (by id). const id = document.getElementById("id").value; const title = document.getElementById("title").value; const name = document.getElementById("name").value; const body = document.getElementById("body").value; //Set the table name. const tableName = "Items"; //Set the parameters for the table const params = { TableName: tableName, // Define the attributes and values of the item to be added. Adding ' + "" ' converts a value to // a string. Item: { id: { N: id + "" }, title: { S: title + "" }, name: { S: name + "" }, body: { S: body + "" }, }, }; // Check that all the fields are completed. if (id != "" && title != "" && name != "" && body != "") { try { //Upload the item to the table await dynamoClient.send(new PutItemCommand(params)); alert("Data added to table."); try { // Create the message parameters object. const messageParams = { Message: "A new item with ID value was added to the DynamoDB", PhoneNumber: "PHONE_NUMBER", //PHONE_NUMBER, in the E.164 phone number structure. // For example, ak standard local formatted number, such as (415) 555-2671, is +14155552671 in E.164 // format, where '1' in the country code. }; // Send the SNS message const data = await snsClient.send(new PublishCommand(messageParams)); console.log( "Success, message published. MessageID is " + data.MessageId, ); } catch (err) { // Display error message if error is not sent console.error(err, err.stack); } } catch (err) { // Display error message if item is no added to table console.error( "An error occurred. Check the console for further information", err, ); } // Display alert if all field are not completed. } else { alert("Enter data in each field."); } }; // Expose the function to the browser window.submitData = submitData;
This example code can be found here on GitHub
Finally, run the following at the command prompt to bundle the JavaScript for this
example in a file named main.js
:
webpack add_data.js --mode development --target web --devtool false -o main.js
Note
For information about installing webpack, see Bundle applications with webpack.
To run the app, open index.html
on your browser.
Delete the resources
As stated at the beginning of this tutorial, be sure to terminate all of the resources you create while going through this tutorial to ensure that you’re not charged. You can do this by deleting the AWS CloudFormation stack you created in the Create the AWS resources topic of this tutorial,as follows:
Open the Stacks page, and select the stack.
Choose Delete.
For more AWS cross-service examples, see AWS SDK for JavaScript cross-service examples.