构建应用程序以将数据提交到 DynamoDB - Amazon SDK for JavaScript
Amazon Web Services 文档中描述的 Amazon Web Services 服务或功能可能因区域而异。要查看适用于中国区域的差异,请参阅 中国的 Amazon Web Services 服务入门 (PDF)

Amazon SDK for JavaScript V3 API 参考指南详细描述了 Amazon SDK for JavaScript 版本 3 (V3) 的所有 API 操作。

本文属于机器翻译版本。若本译文内容与英语原文存在差异,则一律以英文原文为准。

构建应用程序以将数据提交到 DynamoDB

此跨服务 Node.js 教程说明了如何构建一个应用程序,使用户能够向 Amazon DynamoDB 表提交数据。此应用程序使用以下服务:

  • Amazon Identity and Access Management (IAM) 和 Amazon Cognito,用于获取授权和权限。

  • Amazon DynamoDB (DynamoDB),用于创建和更新表。

  • Amazon Simple Notification Service (Amazon SNS),用于在用户更新表格时通知应用程序管理员。

情景

在本教程中,一个 HTML 页面提供了一个基于浏览器的应用程序,用于向 Amazon DynamoDB 表提交数据。当用户更新表格时,该应用程序会使用 Amazon SNS 通知应用程序管理员。


                    提交数据应用程序中,浏览器界面、SDK 和 Amazon 服务之间的关系。

先决条件

完成以下先决任务:

  • 设置项目环境以运行这些 Node TypeScript 示例,并安装所需的 Amazon SDK for JavaScript 和第三方模块。请按照 GitHub 上的说明进行操作。

  • 使用用户凭证创建共享配置文件。有关提供共享凭证文件的更多信息,请参阅《Amazon SDK 和工具参考指南》 中的共享配置和凭证文件

创建 Amazon 资源

此应用程序需要以下资源:

  • Amazon Identity and Access Management (IAM);具有以下权限的未经身份验证的 Amazon Cognito 用户角色:

    • sns:Publish

    • dynamodb:PutItem

  • 一个 DynamoDB 表。

您可以在 Amazon 控制台中手动创建这些资源,但我们建议使用本教程中所述的 Amazon CloudFormation 预置这些资源。

使用 Amazon CloudFormation 创建 Amazon

Amazon CloudFormation 让您能够以可预测、可重复的方式创建和预置 Amazon 基础设施部署。有关 Amazon CloudFormation 的更多信息,请参阅 Amazon CloudFormation 用户指南

使用 Amazon CLI 创建 Amazon CloudFormation 堆栈:

  1. 按照 Amazon CLI 用户指南中的说明安装和配置 Amazon CLI。

  2. 在项目文件夹的根目录中创建一个名为 setup.yaml 的文件,然后将 GitHub 上此处的内容复制到该文件中。

    注意

    Amazon CloudFormation 模板是使用 GitHub 上此处提供的 Amazon CDK 生成的。有关 Amazon CDK 的更多信息,请参阅 Amazon Cloud Development Kit (Amazon CDK) 开发人员指南

  3. 从命令行运行以下命令,将 STACK_NAME 替换为堆栈的唯一名称,将 REGION 替换为您的 Amazon 区域。

    重要

    在一个 Amazon 区域和一个 Amazon 账户中,堆栈名称必须唯一。您最多可指定 128 个字符,支持数字和连字符。

    aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM --region REGION

    有关 create-stack 命令参数的更多信息,请参阅 Amazon CLI 命令参考指南Amazon CloudFormation 用户指南

    要查看创建的资源,请在 Amazon 管理控制台中打开 Amazon CloudFormation,选择堆栈,然后选择资源选项卡。

  4. 创建堆栈后,使用 Amazon SDK for JavaScript 填充 DynamoDB 表,如填充表中所述。

填充表

要填充表,请先创建一个名为 libs 的目录,然后在其中创建一个名为 dynamoClient.js 的文件,再将下面的内容粘贴到其中。将 REGION 替换为您的 Amazon 区域,然后将 IDENTITY_POOL_ID 替换为 Amazon Cognito 身份池 ID。这将创建 DynamoDB 客户端对象。

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 };

此代码可以在 GitHub 上的此处找到。

接下来,在项目文件夹中创建一个 dynamoAppHelperFiles 文件夹,在其中创建一个 update-table.js 文件,然后将 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();

在命令行处,运行以下命令。

node update-table.js

此代码可以在 GitHub 上的此处找到。

为应用程序创建前端页面

在这里,您可以为应用程序创建前端 HTML 浏览器页面。

创建一个 DynamoDBApp 目录,创建一个名为 index.html 的文件,然后从 GitHub 上的此处将代码复制进去。script 元素可添加 main.js 文件,其中包含该示例所需的所有 JavaScript。您将在本教程的后面部分中创建 main.js 文件。index.html 中的其余代码将创建用于捕获用户输入的数据的浏览器页面。

此示例代码可在 GitHub 上的此处找到。

创建浏览器脚本

首先,创建示例所需的服务客户端对象。创建一个 libs 目录,创建 snsClient.js,并将以下代码粘贴到其中。替换每个对象中的 REGIONIDENTITY_POOL_ID

注意

使用您在创建 Amazon 资源 中创建的 Amazon Cognito 身份池的 ID。

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 };

此代码可以在 GitHub 上的此处找到。

要为本示例创建浏览器脚本,请在名为 DynamoDBApp 的文件夹中,使用文件名 add_data.js 创建一个 Node.js 模块,然后将以下代码粘贴到其中。submitData 函数会将数据提交到 DynamoDB 表,并使用 Amazon SNS 向应用程序管理员发送短信。

submitData 函数中,为目标电话号码、在应用程序界面上输入的值以及 Amazon S3 存储桶的名称声明变量。接下来,创建一个用于向表中添加项目的参数对象。如果所有值都不为空,则 submitData 会将项目添加到表中,然后发送消息。请记得使用 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;

此示例代码可在 GitHub 上的此处找到。

最后,在命令提示符中运行以下命令,将本示例的 JavaScript 捆绑到名为 main.js 的文件中:

webpack add_data.js --mode development --target web --devtool false -o main.js
注意

有关安装 Webpack 的信息,请参阅将应用程序与 webpack 捆绑在一起

要运行该应用程序,请在浏览器上打开 index.html

删除资源

如本教程开头所述,请务必在学习本教程时终止您创建的所有资源,以确保系统不会向您收费。您可以通过删除在本教程的创建 Amazon 资源 主题中创建的 Amazon CloudFormation 堆栈来实现此目的,如下所示:

  1. 打开 Amazon 管理控制台中的 Amazon CloudFormation

  2. 打开堆栈页面,然后选择堆栈。

  3. 选择删除

有关更多 Amazon 跨服务示例,请参阅 Amazon SDK for JavaScript 跨服务示例