Hilf uns, das zu verbessernAWS SDK for JavaScriptVersion 3 (V3) -Dokumentation, indem Sie Feedback mithilfe derFeedbackverlinken, oder erstellen Sie ein Issue oder Pull Request aufGitHub
DieAWS SDK for JavaScriptReferenzhandbuch zur V3-APIbeschreibt ausführlich alle API-Operationen für denAWS SDK for JavaScriptVersion 3 (V3).
Die vorliegende Übersetzung wurde maschinell erstellt. Im Falle eines Konflikts oder eines Widerspruchs zwischen dieser übersetzten Fassung und der englischen Fassung (einschließlich infolge von Verzögerungen bei der Übersetzung) ist die englische Fassung maßgeblich.
Erstellen des Browser-Skripts
Dieses Thema ist Teil eines Tutorials, das eineAWS-Anwendung, die Nachrichten sendet und abruft, indem Sie dieAWS SDK for JavaScriptund Amazon Simple Queue Service (Amazon SQS). Um am Anfang des Tutorials zu beginnen, lesen Sie Erstellen einer Beispiel-Messaging-Anwendung.
In diesem Thema erstellen Sie ein Browserskript für die App. Wenn Sie das Browserskript erstellt haben, bündeln Sie es in eine Datei namensmain.js
wie in beschriebenBündelung desJavaScriptaus.
Erstellen Sie eine Datei namens index.js
. Kopieren Sie den Code und fügen Sie ihn einHier aufGitHub
Dieser Code wird in den folgenden Abschnitten erläutert:
Konfiguration
Erstellen Sie zunächst einenlibs
erstellen Sie das erforderliche Amazon SQS SQS-Clientobjekt, indem Sie eine Datei mit dem Namen erstellensqsClient.js
aus. ErsetzenREGION
undIDENTITY_POOL_ID
in jedem.
Verwenden Sie die ID des Amazon Cognito-Identitäten-Pools, den Sie inErstellen derAWSRessourcen aus.
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 }), });
In derindex.js
, importiere das erforderlicheAWS SDK for JavaScriptModule und Befehle. ErsetzenSQS_QUEUE_NAME
mit dem Namen der Amazon SQS Queue, die Sie imErstellen derAWSRessourcen aus.
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
DiepopulateChat
function onload ruft automatisch die URL für die Amazon SQS Queue ab und ruft alle Nachrichten in der Warteschlange ab und zeigt sie an.
$(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); } };
Push-Nachrichten
Der Benutzer wählt seinen Namen aus und gibt seine Nachricht ein und sendet die Nachricht ab, die denpushMessage
Funktion.pushMessage
ruft die Amazon SQS Queue Url ab und sendet dann eine Nachricht mit einem eindeutigen Nachrichten-ID-Wert (einer GUID) den Nachrichtentext und den Benutzer an die Amazon SQS Queue. Es ruft dann alle Nachrichten aus der Amazon SQS Queue ab und zeigt sie an.
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;
Löschen von Nachrichten
purge
löscht die Nachrichten aus der Amazon SQS Queue und von der Benutzeroberfläche.
// 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;
Bündelung desJavaScript
Dieser Comlete-Browser-Skriptcode ist verfügbarHier aufGitHubaus.
Verwenden Sie nun das Webpack, um dasindex.js
undAWS SDK for JavaScriptModule in einer einzigen Datei,main.js
aus.
Wenn Sie es noch nicht getan haben, folgen Sie derVoraussetzungenfür dieses Beispiel, um Webpack zu installieren.
Anmerkung Weitere Informationen zuWebpack, finden Sie unterBündeln von Anwendungen mit Webpackaus.
Führen Sie in der Befehlszeile Folgendes aus, um dieJavaScriptfür dieses Beispiel in eine Datei namens
<index.js>
:webpack index.js --mode development --target web --devtool false -o main.js