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),用于创建和更新表。
亚马逊简单通知服务 (AmazonSNS),用于在用户更新表格时通知应用程序管理员。
情景
在本教程中,有一个HTML页面提供了一个基于浏览器的应用程序,用于向 Amazon DynamoDB 表提交数据。当用户更新表格时SNS,该应用程序使用 Amazon 通知应用程序管理员。
先决条件
完成以下先决任务:
-
设置项目环境以运行这些 Node TypeScript 示例,并安装所需的模块 Amazon SDK for JavaScript 和第三方模块。按照上的说明进行操作 GitHub
。 使用用户凭证创建共享配置文件。有关提供共享凭据文件的更多信息,请参阅和工具参考指南中的共享配置Amazon SDKs和凭据文件。
创建 Amazon 资源
此应用程序需要以下资源:
Amazon Identity and Access Management (IAM) 具有以下权限的未经身份验证的 Amazon Cognito 用户角色:
sns:Publish
dynamodb:PutItem
一个 DynamoDB 表。
您可以在 Amazon 控制台中手动创建这些资源,但我们建议 Amazon CloudFormation 按照本教程中的说明配置这些资源。
使用创建 Amazon 资源 Amazon CloudFormation
Amazon CloudFormation 使您能够以可预测的方式重复创建和配置 Amazon 基础架构部署。有关的更多信息 Amazon CloudFormation,请参阅《Amazon CloudFormation 用户指南》。
要使用以下方法创建 Amazon CloudFormation 堆栈 Amazon CLI:
按照《 Amazon CLI Amazon CLI 用户指南》中的说明进行安装和配置。
在项目文件夹的根目录
setup.yaml
中创建一个名为的文件,然后将此处的内容复制 GitHub到该文件中。 注意
该 Amazon CloudFormation 模板是使用此处 Amazon CDK 提供的模板生成的 GitHub
。有关更多信息 Amazon CDK,请参阅《Amazon Cloud Development Kit (Amazon CDK) 开发人员指南》。 从命令行运行以下命令,替换
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 中打开,选择堆栈,然后选择资源选项卡。
创建堆栈后,使用填充 DynamoDB 表,如中所述。 Amazon SDK for JavaScript 填充表
填充表
要填充表,请先创建一个名为 libs
的目录,然后在其中创建一个名为 dynamoClient.js
的文件,再将下面的内容粘贴到其中。Replace(替换) REGION
改为你所在 Amazon 的地区,然后替换 IDENTITY_POOL_ID
使用亚马逊 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 };
此代码可从此处获
接下来,在项目dynamoAppHelperFiles
文件夹中创建一个文件夹,update-table.js
在其中创建一个文件,然后将此处
// 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
此代码可从此处获
为应用程序创建前端页面
在这里,您可以为应用程序创建前端HTML浏览器页面。
创建一个DynamoDBApp
目录,创建一个名为的文件index.html
,然后从此处script
元素添加main.js
文件,其中包含示例 JavaScript所需的所有内容。您将在本教程的后面部分中创建 main.js
文件。index.html
中的其余代码将创建用于捕获用户输入的数据的浏览器页面。
可以在此处找到此
创建浏览器脚本
首先,创建示例所需的服务客户端对象。创建一个 libs
目录,创建 snsClient.js
,并将以下代码粘贴到其中。Replace(替换) REGION
以及 IDENTITY_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 向SMS应用程序管理员发送文本。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;
可以在此处找到此
最后,在命令提示符下运行以下命令,将本示例的捆绑到名 JavaScript 为的文件中main.js
:
webpack add_data.js --mode development --target web --devtool false -o main.js
注意
有关安装 Webpack 的信息,请参阅将应用程序与 webpack 捆绑在一起。
要运行该应用程序,请在浏览器上打开 index.html
。
删除资源
如本教程开头所述,请务必在学习本教程时终止您创建的所有资源,以确保系统不会向您收费。为此,您可以删除在本教程创建 Amazon 资源 主题中创建的 Amazon CloudFormation 堆栈,如下所示:
打开堆栈页面,然后选择堆栈。
选择删除。
有关更多 Amazon 跨服务示例,请参阅Amazon SDK for JavaScript 跨服务示例。