创建浏览器脚本 - AWS SDK for JavaScript

帮助我们改进AWS SDK for JavaScript版本 3 (V3) 文档,方法是使用反馈链接,或者在上创建议题或拉取请求GitHub.

这些区域有:AWS SDK for JavaScriptV3 API 参考指南详细描述了所有的 API 操作AWS SDK for JavaScript版本 3 (V3)。

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

创建浏览器脚本

本主题是创建AWS通过使用AWS SDK for JavaScript和 Amazon Simple Queue Service (Amazon SQS)。要开始使用本教程,请参阅创建示例消息传递应用

在本主题中,您将为应用程序创建浏览器脚本。创建浏览器脚本后,将其捆绑到名为main.js中所述捆绑JavaScript.

创建一个名为 index.js 的文件。复制并粘贴代码此处GitHub进入它。

以下部分将对此代码进行说明:

配置

首先,创建libs目录通过创建名为的文件来创建所需的 Amazon SQS 客户端对象sqsClient.js. Replace领域IDENTITY_POOL_ID在每个中。

注意

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

import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity"; import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity"; 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模块和命令。ReplaceSQS_QUEUE_NAME使 Amazon SQS 在创建AWS资源 .

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函数 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); } };

推送消息

用户选择他们的姓名并输入他们的消息,然后提交消息,这将启动pushMessagefunction.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

这个 comlete 浏览器脚本代码可用此处GitHub..

现在使用 webpack 来捆绑index.js和AWS SDK for JavaScript将模块放入单个文件中,main.js.

  1. 如果您尚未设置,请按照先决条件对于这个例子来安装 webpack。

    注意

    有关的信息Webpack,请参阅使用 webpack 捆绑应用程序.

  2. 在命令行中运行以下命令以捆绑JavaScript对于这个例子到一个名为的文件<index.js>

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