建置應用程式以將資料提交至 DynamoDB - AWS SDK for JavaScript

AWS SDK for JavaScript V3 API參考指南詳細描述 AWS SDK for JavaScript 第 3 版 (V3) 的所有API操作。

本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。

建置應用程式以將資料提交至 DynamoDB

本跨服務 Node.js 教學課程示範如何建立可讓使用者將資料提交至 Amazon DynamoDB 表格的應用程式。此應用程序使用以下服務:

  • AWS Identity and Access Management(IAM)和 Amazon Cognito 的授權和許可。

  • 用於建立和更新資料表的 Amazon DynamoDB DynamoDB。

  • Amazon Simple Notification Service (Amazon SNS) 可在使用者更新表格時通知應用程式管理員。

該方案

在本教學課程中,HTML 頁面提供了一個以瀏覽器為基礎的應用程式,用於將資料提交至 Amazon DynamoDB 表格。當使用者更新表格時,應用程式會使用 Amazon SNS 通知應用程式管理員。

提交數據應用程序中的瀏覽器界面,SDK 和AWS服務之間的關係。

必要條件

完成下列先決條件工作:

  • 設置項目環境以運行這些節點 TypeScript 示例,並安裝所需AWS SDK for JavaScript的第三方模塊。按照上的說明進行操作 GitHub

  • 透過使用者登入資料建立共用組態檔。有關提供共用認證檔案的詳細資訊,請參閱 AWSSDK 和工具參考指南中的共用設定和認證檔案。

建立資AWS源

此應用程序需要以下資源:

  • AWS Identity and Access Management(IAM) 具有下列許可的未驗證 Amazon Cognito 使用者角色:

    • sns:Publish

    • 動態:PutItem

  • 一個 DynamoDB 資料表。

您可以在AWS主控台中手動建立這些資源,但我們建議您使用本教學課程中所AWS CloudFormation述來佈建這些資源。

使用建立AWS資源 AWS CloudFormation

AWS CloudFormation 可讓您以可預期和重複的方式建立及佈建 AWS 基礎設施部署。如需有關 AWS CloudFormation 的詳細資訊,請參閱《 使用者指南》AWS CloudFormation

要使用以下命AWS CloudFormation令創建堆棧AWS CLI:

  1. 安裝並設定AWS CLI以下AWS CLI使用者指南中的指示。

  2. 在項目文件夾的根目錄setup.yaml中創建一個名為的文件,然後將此處的內容複製 GitHub到其中。

    注意

    AWS CloudFormation範本是使用中AWS CDK提供的來產生的 GitHub。如需關於 AWS CDK 的詳細資訊,請參閱《AWS Cloud Development Kit (AWS CDK) 開發人員指南》。

  3. 從命令行運行以下命令,將 STACK_NAME 替換為堆棧的唯一名稱,並在您所在地區中的 AWS REGION。

    重要

    堆疊名稱在AWS區域和AWS帳戶中必須是唯一的。您最多可以指定 128 個字元,且允許使用數字和連字號。

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

    若要取得有關指create-stack令參數的更多資訊,請參閱《指AWS CLI令參考指南》和《AWS CloudFormation使用指南》

    若要檢視建立的資源,請AWS CloudFormation在AWS管理主控台中開啟,選擇堆疊,然後選取 [資源] 索引標籤。

  4. 建立堆疊時,請使用填AWS SDK for JavaScript入 DynamoDB 表格,如中所述。填入表格

填入表格

要填充表格,請先創建一個名為的目錄libs,並在其中創建一個名為的文件dynamoClient.js,然後將下面的內容粘貼到其中。將區域取代為您的AWS區域,並以亞馬遜認可身分識別碼取代 IDENTITY_POOL_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,並將下面的代碼粘貼到其中。取代每個區域身分識別 _POOL_ID

注意

使用您在建立資AWS源 其中建立的 Amazon Cognito 身分識別集區的識別碼。

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。

若要建立此範例的瀏覽器指令碼,請在名為的資料夾中建立 Node.js 模組DynamoDBAppadd_data.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 的資訊,請參閱捆綁應用程序與網絡包

若要執行應用程式,請在瀏覽器index.html上開啟。

刪除資源

如本教程開頭所述,請務必終止所有你創建的資源,同時通過本教程,以確保你不收費。您可以透過刪除您在本教學課程建立資AWS源 主題中建立的AWS CloudFormation堆疊來執行此操作,如下所示:

  1. AWS管理主控台AWS CloudFormation中開啟。

  2. 開啟「堆疊」頁面,然後選取堆疊。

  3. 選擇刪除

如需更多AWS跨服務範例,請參閱AWS SDK for JavaScript跨服務範例。