メッセージングアプリケーション例の作成 - AWS SDK for JavaScript

AWS SDK for JavaScript V3 APIリファレンスガイドでは、バージョン 3 (V3) のすべてのAPIオペレーションについて詳しく説明しています AWS SDK for JavaScript 。

翻訳は機械翻訳により提供されています。提供された翻訳内容と英語版の間で齟齬、不一致または矛盾がある場合、英語版が優先します。

メッセージングアプリケーション例の作成

AWS SDK for JavaScriptおよびAmazon Simple Queue Service (Amazon SQS) を使用して、メッセージの送信や取得を行うAWSアプリケーションを作成することもできます。メッセージは、メッセージの順序が一貫していることを保証する先入れ先出し (FIFO) キューに保存されます。例えば、キューに保存される最初のメッセージは、キューから読み込まれた最初のメッセージです。

注記

Amazon SQS の詳細については、「What is Amazon Simple Queue Service?」(Amazon Simple Queue Serviceとは?)を参照してください。

このチュートリアルでは、AWSメッセージングという名前のNode.jsアプリケーションを作成します。

完了するためのコスト。このドキュメントに含まれるAWSサービスは、AWS無料利用枠に含まれます。

注意: このチュートリアルを進めるうえで作成したすべてのリソースを終了して、料金が発生しないようにしてください。

前提条件

この例をセットアップして実行するには、まず次のタスクを完了する必要があります。

  • これらの Node TypeScript の例を実行するようにプロジェクト環境を設定し、必要な AWS SDK for JavaScriptおよびサードパーティーモジュールをインストールします。「」の手順に従います GitHub

  • ユーザーの認証情報を使用して、共有設定ファイルを作成します。共有認証情報ファイルの提供の詳細については、「AWS SDK とツールのリファレンスガイド」の「共有設定ファイルおよび認証情報ファイル」を参照してください。

重要

この例では、ECMAScript6 (ES6) を使用しています。これには Node.js バージョン13.x以降が必要です。Node.js の最新バージョンをダウンロードしてインストールするには、「Node.js ダウンロード」を参照してください。

ただし、CommonJS 構文を使用したい場合は、「JavaScript ES6/CommonJS 構文」を参照してください。

AWS リソースを作成します

このチュートリアルでは、以下のリソースが必要です。

  • Amazon SQS のアクセス権限を持つ非認証 IAM ロール。

  • Message.FIFO (メッセージFIFO) という名前の FIFO Amazon SQS キュー - キューの作成についてはAmazon SQS キューの作成を参照してください。

このリソースは手動で作成することもできますが、このチュートリアルで説明するようにAWS CloudFormation(AWS CloudFormation)を使用して、これらのリーソースをプロビジョニングすることをお勧めします。

注記

AWS CloudFormationはソフトウェア開発フレームワークで、クラウドアプリケーションのリソースを定義します。詳細については、『AWS CloudFormation ユーザーガイド』を参照してください。

AWS CloudFormation を使用して AWS リソースを作成します

AWS CloudFormation は、AWS インフラストラクチャデプロイを予想可能および繰り返し作成し、プロビジョニングすることができます。AWS CloudFormation についてはAWS CloudFormationユーザーガイドを参照してください。

AWS CLI を使用して AWS CloudFormation スタックを作成するには:

  1. AWS CLI ユーザーガイド」の手順に従って AWS CLI をインストールして設定します。

  2. プロジェクトフォルダのルートディレクトリsetup.yamlに という名前のファイルを作成し、そこに GitHubコンテンツをコピーします。

    注記

    AWS CloudFormation テンプレートは、 でAWS CDK入手可能な を使用して生成されました。 GitHubAWS CDKの詳細については、AWS Cloud Development Kit (AWS CDK)デベロッパーガイドを参照してください。

  3. コマンドラインから以下のコマンドを実行し、「STACK_NAME」をスタックの一意の名前に置き換えます。

    重要

    スタック名は、AWS 地域および AWS アカウント内で一意である必要があります。最大 128 文字まで指定でき、数字とハイフンを使用できます。

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

    create-stackコマンドパラメータの詳細については、 AWS CLI Command Reference guide(コマンドリファレンスガイド)およびAWS CloudFormation User Guide(ユーザーガイド)を参照してください。

    作成されたリソースを表示するには、AWSマネジメントコンソールでAWS CloudFormationを開き、スタックを選択し、Resources(リソース) タブを選択します。

AWSメッセージングアプリケーションを理解する

SQS キューにメッセージを送信するには、アプリケーションにメッセージを入力し、送信を選択します。

メッセージが送信されると、アプリケーションはメッセージを表示します。

PURGE (パージ) を選択するとAmazon SQS キューからのメッセージをパージすることができます。これにより、キューが空になり、アプリケーションにはメッセージが表示されません。

次に、アプリケーションがメッセージをどのように処理するかを説明します。

  • ユーザは自分の名前を選択してメッセージを入力し、メッセージを送信します。これにより、pushMessage関数が開始します。

  • pushMessageは、Amazon SQS キュー Urlを取得し、一意のメッセージ ID 値 (GUID)、メッセージテキスト、およびユーザーを含むメッセージをAmazon SQS キューに送信します。

  • pushMessageは、Amazon SQS キューからメッセージを取得し、各メッセージのユーザーとメッセージを抽出し、メッセージを表示します。

  • ユーザーはメッセージをパージできます。これにより、Amazon SQS キューとユーザーインターフェイスからメッセージを削除します。

HTMLページを作成する

次に、アプリケーションのグラフィカルユーザーインターフェイス (GUI) に必要な HTML ファイルを作成します。index.html という名前のファイルを作成します。以下のコードをコピーして、index.htmlに貼り付けます。このHTMLはmain.jsを参照します。これは index.js のバンドルバージョンで、必要なAWS SDK for JavaScript モジュールが含まれます。

<!doctype html> <html xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3" > <head> <meta charset="utf-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <link rel="icon" href="./images/favicon.ico" /> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" /> <link rel="stylesheet" href="./css/styles.css" /> <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script> <script src="https://code.jquery.com/ui/1.11.4/jquery-ui.min.js"></script> <script src="./js/main.js"></script> <style> .messageelement { margin: auto; border: 2px solid #dedede; background-color: #d7d1d0; border-radius: 5px; max-width: 800px; padding: 10px; margin: 10px 0; } .messageelement::after { content: ""; clear: both; display: table; } .messageelement img { float: left; max-width: 60px; width: 100%; margin-right: 20px; border-radius: 50%; } .messageelement img.right { float: right; margin-left: 20px; margin-right: 0; } </style> </head> <body> <div class="container"> <h2>AWS Sample Messaging Application</h2> <div id="messages"></div> <div class="input-group mb-3"> <div class="input-group-prepend"> <span class="input-group-text" id="basic-addon1">Sender:</span> </div> <select name="cars" id="username"> <option value="Scott">Brian</option> <option value="Tricia">Tricia</option> </select> </div> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text">Message:</span> </div> <textarea class="form-control" id="textarea" aria-label="With textarea" ></textarea> <button type="button" onclick="pushMessage()" id="send" class="btn btn-success" > Send </button> <button type="button" onclick="purge()" id="refresh" class="btn btn-success" > Purge </button> </div> <!-- All of these child items are hidden and only displayed in a FancyBox ------------------------------------------------------> <div id="hide" style="display: none"> <div id="base" class="messageelement"> <img src="../public/images/av2.png" alt="Avatar" class="right" style="width: 100%" /> <p id="text">Excellent! So, what do you want to do today?</p> <span class="time-right">11:02</span> </div> </div> </div> </body> </html>

このコードは、 でも GitHub入手できます。

ブラウザスクリプトの作成

このトピックでは、アプリケーションのブラウザスクリプトを作成します。ブラウザスクリプトを作成したら、それをのバンドル JavaScriptで説明したようにmain.jsというファイルにバンドルします。

index.js という名前のファイルを作成します。ここからコードをコピーして貼り付け GitHubます。

このコードについては、次のセクションで説明します。

構成

まず、libsディレクトリを作成して、sqsClient.jsという名前のファイルを作成することで、必要な Amazon SQS クライアントオブジェクトを作成します。それぞれのREGIONIDENTITY_POOL_IDを置き換えます。

注記

AWS リソースを作成します で作成したAmazon CognitoアイデンティティプールのIDを使用します。

import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-providers"; import {SQSClient} from "@aws-sdk/client-sqs"; const REGION = "REGION"; //e.g. "us-east-1" const IdentityPoolId = "IDENTITY_POOL_ID"; const sqsClient = new SQSClient({ region: REGION, credentials: fromCognitoIdentityPool({ client: new CognitoIdentityClient({ region: REGION }), identityPoolId: IdentityPoolId }), });

index.jsで、必要なAWS SDK for JavaScriptモジュールとコマンドをインポートします。SQS_QUEUE_NAMEAWS リソースを作成します で作成した Amazon SQS キューの名前に置き換えます。

import { GetQueueUrlCommand, SendMessageCommand, ReceiveMessageCommand, PurgeQueueCommand, } from "@aws-sdk/client-sqs"; import { sqsClient } from "./libs/sqsClient.js"; const QueueName = "SQS_QUEUE_NAME"; // The Amazon SQS queue name, which must end in .fifo for this example.

populateChat

populateChat関数 onload は、Amazon SQS キューの URL を自動的に取得し、キューのすべてのメッセージを取得して表示します。

$(function () { populateChat(); }); const populateChat = async () => { try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; // Get the Amazon SQS Queue URL. const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success. The URL of the SQS Queue is: ", data.QueueUrl); // Set the parameters for retrieving the messages in the Amazon SQS Queue. var getMessageParams = { QueueUrl: data.QueueUrl, MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], VisibilityTimeout: 20, WaitTimeSeconds: 20, }; try { // Retrieve the messages from the Amazon SQS Queue. const data = await sqsClient.send( new ReceiveMessageCommand(getMessageParams) ); console.log("Successfully retrieved messages", data.Messages); // Loop through messages for user and message body. var i; for (i = 0; i < data.Messages.length; i++) { const name = data.Messages[i].MessageAttributes.Name.StringValue; const body = data.Messages[i].Body; // Create the HTML for the message. var userText = body + "<br><br><b>" + name; var myTextNode = $("#base").clone(); myTextNode.text(userText); var image_url; var n = name.localeCompare("Scott"); if (n == 0) image_url = "./images/av1.png"; else image_url = "./images/av2.png"; var images_div = '<img src="' + image_url + '" alt="Avatar" class="right" style=""width:100%;"">'; myTextNode.html(userText); myTextNode.append(images_div); // Add the message to the GUI. $("#messages").append(myTextNode); } } catch (err) { console.log("Error loading messages: ", err); } } catch (err) { console.log("Error retrieving SQS queue URL: ", err); } };

メッセージを転送する

ユーザは自分の名前を選択してメッセージを入力し、メッセージを送信します。これにより、pushMessage関数を開始します。pushMessageは Amazon SQS キュー URLを取得し、一意のメッセージ ID 値 (GUID)とメッセージテキスト、およびユーザーを含むメッセージをAmazon SQS キューに送信します。次に、Amazon SQS キューからすべてのメッセージを取得し、それらを表示します。

const pushMessage = async () => { // Get and convert user and message input. var user = $("#username").val(); var message = $("#textarea").val(); // Create random deduplication ID. var dt = new Date().getTime(); var uuid = "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function ( c ) { var r = (dt + Math.random() * 16) % 16 | 0; dt = Math.floor(dt / 16); return (c == "x" ? r : (r & 0x3) | 0x8).toString(16); }); try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success. The URL of the SQS Queue is: ", data.QueueUrl); // Set the parameters for the message. var messageParams = { MessageAttributes: { Name: { DataType: "String", StringValue: user, }, }, MessageBody: message, MessageDeduplicationId: uuid, MessageGroupId: "GroupA", QueueUrl: data.QueueUrl, }; const result = await sqsClient.send(new SendMessageCommand(messageParams)); console.log("Success", result.MessageId); // Set the parameters for retrieving all messages in the SQS queue. var getMessageParams = { QueueUrl: data.QueueUrl, MaxNumberOfMessages: 10, MessageAttributeNames: ["All"], VisibilityTimeout: 20, WaitTimeSeconds: 20, }; // Retrieve messages from SQS Queue. const final = await sqsClient.send( new ReceiveMessageCommand(getMessageParams) ); console.log("Successfully retrieved", final.Messages); $("#messages").empty(); // Loop through messages for user and message body. var i; for (i = 0; i < final.Messages.length; i++) { const name = final.Messages[i].MessageAttributes.Name.StringValue; const body = final.Messages[i].Body; // Create the HTML for the message. var userText = body + "<br><br><b>" + name; var myTextNode = $("#base").clone(); myTextNode.text(userText); var image_url; var n = name.localeCompare("Scott"); if (n == 0) image_url = "./images/av1.png"; else image_url = "./images/av2.png"; var images_div = '<img src="' + image_url + '" alt="Avatar" class="right" style=""width:100%;"">'; myTextNode.html(userText); myTextNode.append(images_div); // Add the HTML to the GUI. $("#messages").append(myTextNode); } } catch (err) { console.log("Error", err); } }; // Make the function available to the browser window. window.pushMessage = pushMessage;

メッセージをパージする

purgeは、Amazon SQS キューおよびユーザーインターフェイスからメッセージを削除します。

// Delete the message from the Amazon SQS queue. const purge = async () => { try { // Set the Amazon SQS Queue parameters. const queueParams = { QueueName: QueueName, Attributes: { DelaySeconds: "60", MessageRetentionPeriod: "86400", }, }; // Get the Amazon SQS Queue URL. const data = await sqsClient.send(new GetQueueUrlCommand(queueParams)); console.log("Success", data.QueueUrl); // Delete all the messages in the Amazon SQS Queue. const result = await sqsClient.send( new PurgeQueueCommand({ QueueUrl: data.QueueUrl }) ); // Delete all the messages from the GUI. $("#messages").empty(); console.log("Success. All messages deleted.", data); } catch (err) { console.log("Error", err); } }; // Make the function available to the browser window. window.purge = purge;

のバンドル JavaScript

この完全なブラウザスクリプトコードは、 にあります GitHub。

ここで、webpackを使用して、index.jsとAWS SDK for JavaScriptのモジュールを 1つのファイルmain.jsにバンドルします。

  1. webpackのインストールが済んでいない場合は、この例の前提条件に従ってインストールしてください。

    注記

    Webpack の詳細については、Webpack でアプリケーションをバンドルする を参照してください。

  2. コマンドラインで以下を実行して、この例 JavaScript の を <index.js> というファイルにバンドルします。

    webpack index.js --mode development --target web --devtool false -o main.js

次のステップ

お疲れ様でした。Amazon SQS を使用するAWSメッセージングアプリケーションが作成されデプロイされました。このチュートリアルの冒頭で説明したように、チュートリアルを進めるうえで作成したすべてのリソースを終了して、それらに対して料金が発生しないようにしてください。これを行うには、このチュートリアルの AWS リソースを作成します トピックで作成した AWS CloudFormation スタックを以下のように削除します。

  1. AWS マネジメントコンソールで AWS CloudFormation を開きます。

  2. スタック」ページを開き、スタックを選択します。

  3. [削除] をクリックします。