SDK for JavaScript (v3) を使用した Amazon SNS の例 - AWS SDK コードサンプル

Doc AWS SDK Examples リポジトリには、他にも SDK の例があります。 AWS GitHub

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

SDK for JavaScript (v3) を使用した Amazon SNS の例

次のコード例は、Amazon SNS で AWS SDK for JavaScript (v3) を使用してアクションを実行し、一般的なシナリオを実装する方法を示しています。

アクションはより大きなプログラムからのコードの抜粋であり、コンテキスト内で実行する必要があります。アクションは個々のサービス機能を呼び出す方法を示していますが、関連するシナリオやサービス間の例ではアクションのコンテキストが確認できます。

「シナリオ」は、同じサービス内で複数の関数を呼び出して、特定のタスクを実行する方法を示すコード例です。

各例には、 へのリンクが含まれています。このリンクには GitHub、コンテキスト内でコードをセットアップして実行する方法の手順が記載されています。

開始方法

以下のコード例は、Amazon SNS の使用を開始する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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 の詳細については、「 API リファレンスListTopics」の「」を参照してください。 AWS SDK for JavaScript

アクション

次のコードサンプルは、電話番号が Amazon SNS メッセージの受信をオプトアウトしているかを確認する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスCheckIfPhoneNumberIsOptedOut」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、以前の Subscribe アクションでエンドポイントに送信したトークンを検証することによって、エンドポイントの所有者が Amazon SNS メッセージを受信することを希望しているか確認する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスConfirmSubscription」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、Amazon SNS トピックを作成する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスCreateTopic」の「」を参照してください。 AWS SDK for JavaScript

以下のコードサンプルで、Amazon SNS サブスクリプションを削除する方法を示します。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Unsubscribe」を参照してください。

次のコードサンプルは、Amazon SNS トピックとそのトピックに対するすべてのサブスクリプションを削除する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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 // } // } };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスDeleteTopic」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、Amazon SNS トピックのプロパティを取得する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスGetTopicAttributes」の「」を参照してください。 AWS SDK for JavaScript

SDK for JavaScript (v2)
注記

については、こちらを参照してください 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); });
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスGetTopicAttributes」の「」を参照してください。 AWS SDK for JavaScript

次のコードの例は、Amazon SNS SMS メッセージを送信するための設定を取得する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「GetSMSAttributes」を参照してください。

次のコードサンプルは、Amazon SNS トピックのサブスクライバーのリストを取得する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスListSubscriptions」の「」を参照してください。 AWS SDK for JavaScript

次のコードサンプルは、Amazon SNS トピックを一覧表示する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスListTopics」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Amazon SNS を使用し、属性を指定してメッセージを発行する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

グループ、重複、属性のオプションを指定してメッセージをトピックに発行します。

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(); } }
  • API の詳細については、AWS SDK for JavaScriptAPI リファレンスの「発行」を参照してください。

次のコードサンプルは、Amazon SNS トピックにメッセージを発行する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScriptAPI リファレンスの「発行」を参照してください。

次のコードの例は、Amazon SNS を使用した SMS メッセージを送信するためのデフォルト設定を設定する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「SetSMSAttributes」を参照してください。

以下のコードサンプルは、Amazon SNS トピック属性を設定する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、「 API リファレンスSetTopicAttributes」の「」を参照してください。 AWS SDK for JavaScript

次のコード例は、Lambda 関数をサブスクライブし、Amazon SNS トピックから通知を受信するようにする方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Subscribe」を参照してください。

次のコード例は、モバイルアプリケーションエンドポイントをサブスクライブし、Amazon SNS トピックから通知を受信するようにする方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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 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; };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Subscribe」を参照してください。

次のコード例は、Amazon SQS キューをサブスクライブして Amazon SNS トピックから通知を受信する方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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; };
  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Subscribe」を参照してください。

次のコードスニペットは、Amazon SNS トピックに E メールアドレスをサブスクライブする方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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' // } };
  • 詳細については、AWS SDK for JavaScript デベロッパーガイドを参照してください。

  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Subscribe」を参照してください。

次のコードスニペットは、Amazon SNS トピックにフィルターでサブスクライブする方法を示しています。

SDK for JavaScript (v3)
注記

については、こちらを参照してください GitHub。用例一覧を検索し、AWS コードサンプルリポジトリでの設定と実行の方法を確認してください。

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; };
  • API の詳細については、AWS SDK for JavaScript API リファレンスの「Subscribe」を参照してください。

シナリオ

次のコードサンプルは、以下の操作方法を示しています。

  • トピック (FIFO または非 FIFO) を作成します。

  • フィルターを適用するオプションを使用して、複数のキューをトピックにサブスクライブします。

  • メッセージをトピックに発行します。

  • キューをポーリングして受信メッセージを確認します。

SDK for JavaScript (v3)
注記

については、こちらを参照してください 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-sdk-examples/libs/prompter.js"; import { SlowLogger } from "@aws-sdk-examples/libs/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(); } } }