Amazon SNS 示例使用 SDK for JavaScript (v3) - AWS SDK 程式碼範例

AWS 文檔 AWS SDK示例 GitHub 回購中有更多SDK示例

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

Amazon SNS 示例使用 SDK for JavaScript (v3)

下列程式碼範例說明如何透過使用 AWS SDK for JavaScript (v3) 搭配 Amazon 來執行動作和實作常見案例SNS。

Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會顯示如何呼叫個別服務函數,但您可以在其相關案例中查看內容中的動作。

例是程式碼範例,向您展示如何透過呼叫服務中的多個函數或與其他函式結合來完成特定工作 AWS 服務。

每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。

開始使用

下列程式碼範例說明如何開始使用 Amazon SNS。

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

初始化SNS客戶端並列出您帳戶中的主題。

import { SNSClient, paginateListTopics } from "@aws-sdk/client-sns"; export const helloSns = async () => { // The configuration object (`{}`) is required. If the region and credentials // are omitted, the SDK uses your local configuration if it exists. const client = new SNSClient({}); // You can also use `ListTopicsCommand`, but to use that command you must // handle the pagination yourself. You can do that by sending the `ListTopicsCommand` // with the `NextToken` parameter from the previous request. const paginatedTopics = paginateListTopics({ client }, {}); const topics = []; for await (const page of paginatedTopics) { if (page.Topics?.length) { topics.push(...page.Topics); } } const suffix = topics.length === 1 ? "" : "s"; console.log( `Hello, Amazon SNS! You have ${topics.length} topic${suffix} in your account.`, ); console.log(topics.map((t) => ` * ${t.TopicArn}`).join("\n")); };
  • 如需詳API細資訊,請參閱AWS SDK for JavaScript API參考ListTopics中的。

動作

下列程式碼範例會示範如何使用CheckIfPhoneNumberIsOptedOut

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const checkIfPhoneNumberIsOptedOut = async ( phoneNumber = "5555555555", ) => { const command = new CheckIfPhoneNumberIsOptedOutCommand({ phoneNumber, }); const response = await snsClient.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // isOptedOut: false // } return response; };

下列程式碼範例會示範如何使用ConfirmSubscription

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { ConfirmSubscriptionCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} token - This token is sent the subscriber. Only subscribers * that are not AWS services (HTTP/S, email) need to be confirmed. * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. */ export const confirmSubscription = async ( token = "TOKEN", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( // A subscription only needs to be confirmed if the endpoint type is // HTTP/S, email, or in another AWS account. new ConfirmSubscriptionCommand({ Token: token, TopicArn: topicArn, // If this is true, the subscriber cannot unsubscribe while unauthenticated. AuthenticateOnUnsubscribe: "false", }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '4bb5bce9-805a-5517-8333-e1d2cface90b', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

下列程式碼範例會示範如何使用CreateTopic

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { CreateTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicName - The name of the topic to create. */ export const createTopic = async (topicName = "TOPIC_NAME") => { const response = await snsClient.send( new CreateTopicCommand({ Name: topicName }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '087b8ad2-4593-50c4-a496-d7e90b82cf3e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:TOPIC_NAME' // } return response; };

下列程式碼範例會示範如何使用DeleteTopic

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { DeleteTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to delete. */ export const deleteTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new DeleteTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'a10e2886-5a8f-5114-af36-75bd39498332', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } };

下列程式碼範例會示範如何使用GetSMSAttributes

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { GetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const getSmsAttributes = async () => { const response = await snsClient.send( // If you have not modified the account-level mobile settings of SNS, // the DefaultSMSType is undefined. For this example, it was set to // Transactional. new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // attributes: { DefaultSMSType: 'Transactional' } // } return response; };

下列程式碼範例會示範如何使用GetTopicAttributes

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { GetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic to retrieve attributes for. */ export const getTopicAttributes = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new GetTopicAttributesCommand({ TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '36b6a24e-5473-5d4e-ac32-ff72d9a73d94', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Attributes: { // Policy: '{...}', // Owner: 'xxxxxxxxxxxx', // SubscriptionsPending: '1', // TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic', // TracingConfig: 'PassThrough', // EffectiveDeliveryPolicy: '{"http":{"defaultHealthyRetryPolicy":{"minDelayTarget":20,"maxDelayTarget":20,"numRetries":3,"numMaxDelayRetries":0,"numNoDelayRetries":0,"numMinDelayRetries":0,"backoffFunction":"linear"},"disableSubscriptionOverrides":false,"defaultRequestPolicy":{"headerContentType":"text/plain; charset=UTF-8"}}}', // SubscriptionsConfirmed: '0', // DisplayName: '', // SubscriptionsDeleted: '1' // } // } return response; };
SDK對於 JavaScript (第 2 個)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

匯入SDK和用戶端模組並呼叫API.

// Load the AWS SDK for Node.js var AWS = require("aws-sdk"); // Set region AWS.config.update({ region: "REGION" }); // Create promise and SNS service object var getTopicAttribsPromise = new AWS.SNS({ apiVersion: "2010-03-31" }) .getTopicAttributes({ TopicArn: "TOPIC_ARN" }) .promise(); // Handle promise's fulfilled/rejected states getTopicAttribsPromise .then(function (data) { console.log(data); }) .catch(function (err) { console.error(err, err.stack); });

下列程式碼範例會示範如何使用ListSubscriptions

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { ListSubscriptionsByTopicCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to list subscriptions. */ export const listSubscriptionsByTopic = async (topicArn = "TOPIC_ARN") => { const response = await snsClient.send( new ListSubscriptionsByTopicCommand({ TopicArn: topicArn }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0934fedf-0c4b-572e-9ed2-a3e38fadb0c8', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Subscriptions: [ // { // SubscriptionArn: 'PendingConfirmation', // Owner: '901487484989', // Protocol: 'email', // Endpoint: 'corepyle@amazon.com', // TopicArn: 'arn:aws:sns:us-east-1:901487484989:mytopic' // } // ] // } return response; };

下列程式碼範例會示範如何使用ListTopics

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { ListTopicsCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const listTopics = async () => { const response = await snsClient.send(new ListTopicsCommand({})); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '936bc5ad-83ca-53c2-b0b7-9891167b909e', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // Topics: [ { TopicArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic' } ] // } return response; };

下列程式碼範例會示範如何使用Publish

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { PublishCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object * if you are using the `json` `MessageStructure`. * @param {string} topicArn - The ARN of the topic to which you would like to publish. */ export const publish = async ( message = "Hello from SNS!", topicArn = "TOPIC_ARN", ) => { const response = await snsClient.send( new PublishCommand({ Message: message, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

將訊息發佈至具有群組、複寫和屬性選項的主題。

async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId, deduplicationId, choices; if (this.isFifo) { await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); } choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId ? { MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } }

下列程式碼範例會示範如何使用SetSMSAttributes

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { SetSMSAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {"Transactional" | "Promotional"} defaultSmsType */ export const setSmsType = async (defaultSmsType = "Transactional") => { const response = await snsClient.send( new SetSMSAttributesCommand({ attributes: { // Promotional – (Default) Noncritical messages, such as marketing messages. // Transactional – Critical messages that support customer transactions, // such as one-time passcodes for multi-factor authentication. DefaultSMSType: defaultSmsType, }, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '1885b977-2d7e-535e-8214-e44be727e265', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };

下列程式碼範例會示範如何使用SetTopicAttributes

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { SetTopicAttributesCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; export const setTopicAttributes = async ( topicArn = "TOPIC_ARN", attributeName = "DisplayName", attributeValue = "Test Topic", ) => { const response = await snsClient.send( new SetTopicAttributesCommand({ AttributeName: attributeName, AttributeValue: attributeValue, TopicArn: topicArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'd1b08d0e-e9a4-54c3-b8b1-d03238d2b935', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };

下列程式碼範例會示範如何使用Subscribe

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic for which you wish to confirm a subscription. * @param {string} emailAddress - The email address that is subscribed to the topic. */ export const subscribeEmail = async ( topicArn = "TOPIC_ARN", emailAddress = "usern@me.com", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "email", TopicArn: topicArn, Endpoint: emailAddress, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } };

訂閱某個主題的行動應用程式。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of an application. This endpoint is created * when an application registers for notifications. */ export const subscribeApp = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "application", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

訂閱某個主題的 Lambda 函數。

import { SubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} topicArn - The ARN of the topic the subscriber is subscribing to. * @param {string} endpoint - The Endpoint ARN of and AWS Lambda function. */ export const subscribeLambda = async ( topicArn = "TOPIC_ARN", endpoint = "ENDPOINT", ) => { const response = await snsClient.send( new SubscribeCommand({ Protocol: "lambda", TopicArn: topicArn, Endpoint: endpoint, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: 'c8e35bcd-b3c0-5940-9f66-06f6fcc108f0', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'pending confirmation' // } return response; };

訂閱SQS佇列以取得主題。

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueue = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

使用篩選器訂閱主題。

import { SubscribeCommand, SNSClient } from "@aws-sdk/client-sns"; const client = new SNSClient({}); export const subscribeQueueFiltered = async ( topicArn = "TOPIC_ARN", queueArn = "QUEUE_ARN", ) => { const command = new SubscribeCommand({ TopicArn: topicArn, Protocol: "sqs", Endpoint: queueArn, Attributes: { // This subscription will only receive messages with the 'event' attribute set to 'order_placed'. FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ event: ["order_placed"], }), }, }); const response = await client.send(command); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '931e13d9-5e2b-543f-8781-4e9e494c5ff2', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // }, // SubscriptionArn: 'arn:aws:sns:us-east-1:xxxxxxxxxxxx:subscribe-queue-test-430895:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx' // } return response; };

下列程式碼範例會示範如何使用Unsubscribe

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

在單獨的模組中建立用戶端並將其匯出。

import { SNSClient } from "@aws-sdk/client-sns"; // The AWS Region can be provided here using the `region` property. If you leave it blank // the SDK will default to the region set in your AWS config. export const snsClient = new SNSClient({});

匯入SDK和用戶端模組並呼叫API.

import { UnsubscribeCommand } from "@aws-sdk/client-sns"; import { snsClient } from "../libs/snsClient.js"; /** * @param {string} subscriptionArn - The ARN of the subscription to cancel. */ const unsubscribe = async ( subscriptionArn = "arn:aws:sns:us-east-1:xxxxxxxxxxxx:mytopic:xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx", ) => { const response = await snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn, }), ); console.log(response); // { // '$metadata': { // httpStatusCode: 200, // requestId: '0178259a-9204-507c-b620-78a7570a44c6', // extendedRequestId: undefined, // cfId: undefined, // attempts: 1, // totalRetryDelay: 0 // } // } return response; };

案例

下列程式碼範例顯示如何建立將資料提交至 Amazon DynamoDB 表的應用程式,並在使用者更新表格時通知您。

SDK對於 JavaScript (3)

此範例說明如何建立可讓使用者將資料提交至 Amazon DynamoDB 表格的應用程式,以及如何使用 Amazon 簡單通知服務 (AmazonSNS) 傳送文字訊息給管理員。

有關如何設置和運行的完整源代碼和說明,請參閱中的完整示例GitHub

此範例也可在 AWS SDK for JavaScript v3 開發人員指南中取得。

此範例中使用的服務
  • DynamoDB

  • Amazon SNS

下列程式碼範例示範如何建立無伺服器應用程式,讓使用者以標籤管理相片。

SDK對於 JavaScript (3)

顯示如何開發照片資產管理應用程式,以便使用 Amazon Rekognition 偵測圖片中的標籤,並將其儲存以供日後擷取。

有關如何設置和運行的完整源代碼和說明,請參閱中的完整示例 GitHub

如要深入探索此範例的來源,請參閱 AWS  社群上的文章。

此範例中使用的服務
  • API閘道

  • DynamoDB

  • Lambda

  • Amazon Rekognition

  • Amazon S3

  • Amazon SNS

下列程式碼範例顯示如何透過互動式應用程式探索 Amazon Textract 輸出。

SDK對於 JavaScript (3)

示範如何使用建置 React 應用程式,該應用程式使用 Amazon Textract 擷取文件影像中的資料,並將其顯示在互動式網頁中。 AWS SDK for JavaScript 此範例會在 Web 瀏覽器中執行,且登入資料需要經過驗證的 Amazon Cognito 身分。它使用 Amazon 簡單存儲服務(Amazon S3)進行存儲,並對於通知,它會輪詢訂閱 Amazon 簡單通知服務(AmazonSQS)主題的 Amazon 簡單隊列(亞馬遜SNS)隊列。

有關如何設置和運行的完整源代碼和說明,請參閱中的完整示例GitHub

此範例中使用的服務
  • Amazon Cognito Identity

  • Amazon S3

  • Amazon SNS

  • Amazon SQS

  • Amazon Textract

以下程式碼範例顯示做法:

  • 創建主題(FIFO或非FIFO)。

  • 為主題訂閱多個佇列,並提供套用篩選條件的選擇。

  • 發佈訊息至主題。

  • 輪詢佇列以獲取收到的訊息。

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫中設定和執行。

這是此工作流程的進入點。

import { SNSClient } from "@aws-sdk/client-sns"; import { SQSClient } from "@aws-sdk/client-sqs"; import { TopicsQueuesWkflw } from "./TopicsQueuesWkflw.js"; import { Prompter } from "@aws-doc-sdk-examples/lib/prompter.js"; import { SlowLogger } from "@aws-doc-sdk-examples/lib/slow-logger.js"; export const startSnsWorkflow = () => { const noLoggerDelay = process.argv.find((arg) => arg === "--no-logger-delay"); const snsClient = new SNSClient({}); const sqsClient = new SQSClient({}); const prompter = new Prompter(); const logger = noLoggerDelay ? console : new SlowLogger(25); const wkflw = new TopicsQueuesWkflw(snsClient, sqsClient, prompter, logger); wkflw.start(); };

先前的程式碼提供了必要的相依性並啟動工作流程。下一節包含範例的大量內容。

const toneChoices = [ { name: "cheerful", value: "cheerful" }, { name: "funny", value: "funny" }, { name: "serious", value: "serious" }, { name: "sincere", value: "sincere" }, ]; export class TopicsQueuesWkflw { // SNS topic is configured as First-In-First-Out isFifo = true; // Automatic content-based deduplication is enabled. autoDedup = false; snsClient; sqsClient; topicName; topicArn; subscriptionArns = []; /** * @type {{ queueName: string, queueArn: string, queueUrl: string, policy?: string }[]} */ queues = []; prompter; /** * @param {import('@aws-sdk/client-sns').SNSClient} snsClient * @param {import('@aws-sdk/client-sqs').SQSClient} sqsClient * @param {import('../../libs/prompter.js').Prompter} prompter * @param {import('../../libs/logger.js').Logger} logger */ constructor(snsClient, sqsClient, prompter, logger) { this.snsClient = snsClient; this.sqsClient = sqsClient; this.prompter = prompter; this.logger = logger; } async welcome() { await this.logger.log(MESSAGES.description); } async confirmFifo() { await this.logger.log(MESSAGES.snsFifoDescription); this.isFifo = await this.prompter.confirm({ message: MESSAGES.snsFifoPrompt, }); if (this.isFifo) { this.logger.logSeparator(MESSAGES.headerDedup); await this.logger.log(MESSAGES.deduplicationNotice); await this.logger.log(MESSAGES.deduplicationDescription); this.autoDedup = await this.prompter.confirm({ message: MESSAGES.deduplicationPrompt, }); } } async createTopic() { await this.logger.log(MESSAGES.creatingTopics); this.topicName = await this.prompter.input({ message: MESSAGES.topicNamePrompt, }); if (this.isFifo) { this.topicName += ".fifo"; this.logger.logSeparator(MESSAGES.headerFifoNaming); await this.logger.log(MESSAGES.appendFifoNotice); } const response = await this.snsClient.send( new CreateTopicCommand({ Name: this.topicName, Attributes: { FifoTopic: this.isFifo ? "true" : "false", ...(this.autoDedup ? { ContentBasedDeduplication: "true" } : {}), }, }), ); this.topicArn = response.TopicArn; await this.logger.log( MESSAGES.topicCreatedNotice .replace("${TOPIC_NAME}", this.topicName) .replace("${TOPIC_ARN}", this.topicArn), ); } async createQueues() { await this.logger.log(MESSAGES.createQueuesNotice); // Increase this number to add more queues. let maxQueues = 2; for (let i = 0; i < maxQueues; i++) { await this.logger.log(MESSAGES.queueCount.replace("${COUNT}", i + 1)); let queueName = await this.prompter.input({ message: MESSAGES.queueNamePrompt.replace( "${EXAMPLE_NAME}", i === 0 ? "good-news" : "bad-news", ), }); if (this.isFifo) { queueName += ".fifo"; await this.logger.log(MESSAGES.appendFifoNotice); } const response = await this.sqsClient.send( new CreateQueueCommand({ QueueName: queueName, Attributes: { ...(this.isFifo ? { FifoQueue: "true" } : {}) }, }), ); const { Attributes } = await this.sqsClient.send( new GetQueueAttributesCommand({ QueueUrl: response.QueueUrl, AttributeNames: ["QueueArn"], }), ); this.queues.push({ queueName, queueArn: Attributes.QueueArn, queueUrl: response.QueueUrl, }); await this.logger.log( MESSAGES.queueCreatedNotice .replace("${QUEUE_NAME}", queueName) .replace("${QUEUE_URL}", response.QueueUrl) .replace("${QUEUE_ARN}", Attributes.QueueArn), ); } } async attachQueueIamPolicies() { for (const [index, queue] of this.queues.entries()) { const policy = JSON.stringify( { Statement: [ { Effect: "Allow", Principal: { Service: "sns.amazonaws.com", }, Action: "sqs:SendMessage", Resource: queue.queueArn, Condition: { ArnEquals: { "aws:SourceArn": this.topicArn, }, }, }, ], }, null, 2, ); if (index !== 0) { this.logger.logSeparator(); } await this.logger.log(MESSAGES.attachPolicyNotice); console.log(policy); const addPolicy = await this.prompter.confirm({ message: MESSAGES.addPolicyConfirmation.replace( "${QUEUE_NAME}", queue.queueName, ), }); if (addPolicy) { await this.sqsClient.send( new SetQueueAttributesCommand({ QueueUrl: queue.queueUrl, Attributes: { Policy: policy, }, }), ); queue.policy = policy; } else { await this.logger.log( MESSAGES.policyNotAttachedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } } async subscribeQueuesToTopic() { for (const [index, queue] of this.queues.entries()) { /** * @type {import('@aws-sdk/client-sns').SubscribeCommandInput} */ const subscribeParams = { TopicArn: this.topicArn, Protocol: "sqs", Endpoint: queue.queueArn, }; let tones = []; if (this.isFifo) { if (index === 0) { await this.logger.log(MESSAGES.fifoFilterNotice); } tones = await this.prompter.checkbox({ message: MESSAGES.fifoFilterSelect.replace( "${QUEUE_NAME}", queue.queueName, ), choices: toneChoices, }); if (tones.length) { subscribeParams.Attributes = { FilterPolicyScope: "MessageAttributes", FilterPolicy: JSON.stringify({ tone: tones, }), }; } } const { SubscriptionArn } = await this.snsClient.send( new SubscribeCommand(subscribeParams), ); this.subscriptionArns.push(SubscriptionArn); await this.logger.log( MESSAGES.queueSubscribedNotice .replace("${QUEUE_NAME}", queue.queueName) .replace("${TOPIC_NAME}", this.topicName) .replace("${TONES}", tones.length ? tones.join(", ") : "none"), ); } } async publishMessages() { const message = await this.prompter.input({ message: MESSAGES.publishMessagePrompt, }); let groupId, deduplicationId, choices; if (this.isFifo) { await this.logger.log(MESSAGES.groupIdNotice); groupId = await this.prompter.input({ message: MESSAGES.groupIdPrompt, }); if (this.autoDedup === false) { await this.logger.log(MESSAGES.deduplicationIdNotice); deduplicationId = await this.prompter.input({ message: MESSAGES.deduplicationIdPrompt, }); } choices = await this.prompter.checkbox({ message: MESSAGES.messageAttributesPrompt, choices: toneChoices, }); } await this.snsClient.send( new PublishCommand({ TopicArn: this.topicArn, Message: message, ...(groupId ? { MessageGroupId: groupId, } : {}), ...(deduplicationId ? { MessageDeduplicationId: deduplicationId, } : {}), ...(choices ? { MessageAttributes: { tone: { DataType: "String.Array", StringValue: JSON.stringify(choices), }, }, } : {}), }), ); const publishAnother = await this.prompter.confirm({ message: MESSAGES.publishAnother, }); if (publishAnother) { await this.publishMessages(); } } async receiveAndDeleteMessages() { for (const queue of this.queues) { const { Messages } = await this.sqsClient.send( new ReceiveMessageCommand({ QueueUrl: queue.queueUrl, }), ); if (Messages) { await this.logger.log( MESSAGES.messagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); console.log(Messages); await this.sqsClient.send( new DeleteMessageBatchCommand({ QueueUrl: queue.queueUrl, Entries: Messages.map((message) => ({ Id: message.MessageId, ReceiptHandle: message.ReceiptHandle, })), }), ); } else { await this.logger.log( MESSAGES.noMessagesReceivedNotice.replace( "${QUEUE_NAME}", queue.queueName, ), ); } } const deleteAndPoll = await this.prompter.confirm({ message: MESSAGES.deleteAndPollConfirmation, }); if (deleteAndPoll) { await this.receiveAndDeleteMessages(); } } async destroyResources() { for (const subscriptionArn of this.subscriptionArns) { await this.snsClient.send( new UnsubscribeCommand({ SubscriptionArn: subscriptionArn }), ); } for (const queue of this.queues) { await this.sqsClient.send( new DeleteQueueCommand({ QueueUrl: queue.queueUrl }), ); } if (this.topicArn) { await this.snsClient.send( new DeleteTopicCommand({ TopicArn: this.topicArn }), ); } } async start() { console.clear(); try { this.logger.logSeparator(MESSAGES.headerWelcome); await this.welcome(); this.logger.logSeparator(MESSAGES.headerFifo); await this.confirmFifo(); this.logger.logSeparator(MESSAGES.headerCreateTopic); await this.createTopic(); this.logger.logSeparator(MESSAGES.headerCreateQueues); await this.createQueues(); this.logger.logSeparator(MESSAGES.headerAttachPolicy); await this.attachQueueIamPolicies(); this.logger.logSeparator(MESSAGES.headerSubscribeQueues); await this.subscribeQueuesToTopic(); this.logger.logSeparator(MESSAGES.headerPublishMessage); await this.publishMessages(); this.logger.logSeparator(MESSAGES.headerReceiveMessages); await this.receiveAndDeleteMessages(); } catch (err) { console.error(err); } finally { await this.destroyResources(); } } }

無伺服器範例

下列程式碼範例示範如何實作 Lambda 函數,該函數會接收由接收來自SNS主題的訊息而觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。

SDK對於 JavaScript (3)
注意

還有更多關於 GitHub。尋找完整範例,並了解如何在無伺服器範例儲存庫中設定和執行。

使 Lambda JavaScript. SNS

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record) { try { const message = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }

使 Lambda TypeScript. SNS

// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda"; export const functionHandler: SNSHandler = async ( event: SNSEvent, context: Context ): Promise<void> => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record: SNSEventRecord): Promise<any> { try { const message: string = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }