Amazon SNS でのサブスクリプションの管理 - AWS SDK for JavaScript

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

Amazon SNS でのサブスクリプションの管理

JavaScript code example that applies to Node.js execution

この Node.js コード例は以下を示しています。

  • Amazon SNS トピックへのすべてのサブスクリプションを一覧表示する方法。

  • E メールアドレス、アプリケーションエンドポイント、または AWS Lambda 関数を Amazon SNS トピックにサブスクライブする方法。

  • Amazon SNS トピックのサブスクライブを解除する方法。

シナリオ

この例では、一連の Node.js モジュールを使用して通知メッセージを Amazon SNS トピックに発行します。Node.js モジュールは、SNS クライアントクラスの以下のメソッドを使用してトピックを管理するために SDK for JavaScript を使用します。

前提条件タスク

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

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

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

重要

これらの例は、ECMAScript6 (ES6) を使用してクライアントサービスオブジェクトとコマンドをimport/export する方法を示します。

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

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

サブスクリプションのトピックへの一覧表示

この例では、Node.js モジュールを使用して Amazon SNS トピックへのすべてのサブスクリプションを一覧表示します。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

list-subscriptions-by-topic.jsというファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

サブスクリプションを一覧表示するトピックの TopicArn パラメータを含むオブジェクトを作成します。ListSubscriptionsByTopicCommand クライアントクラスの SNS メソッドにパラメータを渡します。ListSubscriptionsByTopicCommand メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_ARN をサブスクリプションを一覧表示したいトピックのAmazon リソースネーム (ARN) に置き換えてください。

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; };

この例を実行するには、コマンドプロンプトで以下を入力します。

node list-subscriptions-by-topic.js

このサンプルコードは、このGitHubにで見つけられます。

E メールアドレスのトピックへのサブスクライブ

この例では、Node.js モジュールを使用して E メールアドレスをサブスクライブし、Amazon SNS トピックから SMTP E メールメッセージを受信するようにします。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

subscribe-email.jsというファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

Protocol プロトコル、サブスクライブするトピックの email、およびメッセージの TopicArn としての E メールアドレスを指定するための Endpoint パラメータを含むオブジェクトを作成します。SubscribeCommand クライアントクラスの SNS メソッドにパラメータを渡します。このトピックの他の例が示すように、渡されたパラメータに使用される値に応じて、subscribe メソッドを使用して Amazon SNS トピックにいくつかの異なるエンドポイントをサブスクライブすることができます。

SubscribeCommand メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_ARN をトピックの Amazon リソースネーム (ARN) に、EMAIL_ADDRESS をサブスクライブする E メールアドレスに置き換えます。

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' // } };

この例を実行するには、コマンドプロンプトで以下を入力します。

node subscribe-email.js

このサンプルコードは、このGitHubにで見つけられます。

サブスクリプションを確認する

この例では、Node.jsモジュールを使用し、以前の Subscribe アクションでエンドポイントに送信したトークンを検証することによって、メッセージを受信するというエンドポイントの所有者の意思を確認します。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

confirm-subscription.jsというファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

TOPIC_ARNTOKENを含むパラメータを定義し、AuthenticateOnUnsubscribeに対してTRUEまたはFALSEの値を定義します。

トークンは、以前のSUBSCRIBEアクションの期間にエンドポイントの所有者に送信される短期間のトークンです。たとえば、電子メールエンドポイントの場合、TOKENは、E メールの所有者に送信されたサブスクリプションの確認メールのURLにあります。例えば、abc123は次のURLのトークンです。

Amazon Web Services Simple Notification Service subscription confirmation page.

ConfirmSubscriptionCommandメソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_ARNをトピックの Amazon リソースネーム (ARN)に、TOKENを以前のSubscribeアクションでエンドポイント所有者に送信されたURLのトークン値に置き換えてください。そして、定義AuthenticateOnUnsubscribeTRUEFALSEの値で定義します。

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; };

この例を実行するには、コマンドプロンプトで以下を入力します。

node confirm-subscription.js

このサンプルコードは、このGitHubにで見つけられます。

アプリケーションエンドポイントのトピックへのサブスクライブ

この例では、Node.js モジュールを使用してモバイルアプリケーションのエンドポイントをサブスクライブし、Amazon SNS トピックから通知を受信するようにします。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

subscribe-app.jsというファイル名で Node.js モジュールを作成します。必要なモジュールとパッケージのインストールを含め、前述のようにSDKを設定します。

applicationプロトコルを指定するProtocolパラメータ、サブスクライブするトピックのTopicArn、そしてEndpointパラメータのモバイルアプリケーションエンドポイントのAmazon リソースネーム(ARN)を含むオフジェクトを作成します。SubscribeCommand クライアントクラスの SNS メソッドにパラメータを渡します。

SubscribeCommandメソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_ARN をトピックのAmazon リソースネーム (ARN)に、 MOBILE_ENDPOINT_ARN をトピックスにサブスクライブしているエンドポイントに置き換えてください。

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; };

この例を実行するには、コマンドプロンプトで以下を入力します。

node subscribe-app.js

このサンプルコードは、このGitHubにで見つけられます。

Lambda 関数のトピックへのサブスクライブ

この例では、Node.js モジュールを使用して AWS Lambda 関数をサブスクライブし、Amazon SNS トピックから通知を受け取るようにします。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

subscribe-lambda.jsというファイル名で Node.js モジュールを作成します。前に示したように SDK を設定します。

Protocol パラメータを含むオブジェクトを作成し、lambda プロトコル、サブスクライブするトピックのTopicArn、およびAWS Lambda関数のAmazon Resource Name ARN をEndpoint パラメータとして指定します。SubscribeCommand クライアントクラスの SNS メソッドにパラメータを渡します。

SubscribeCommand メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_ARN をトピックの Amazon リソースネーム(ARN)に、RAMBDA_FUNCTION_ARNをLambda 関数のAmazonリソースネーム(ARN)に置き換えてください。

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; };

この例を実行するには、コマンドプロンプトで以下を入力します。

node subscribe-lambda.js

このサンプルコードは、このGitHubにで見つけられます。

トピックからのサブスクリプションの解除

この例では、Node.js モジュールを使用して Amazon SNS トピックのサブスクリプションを解除します。

libsディレクトリを作成し、ファイル名snsClient.jsでNode.js モジュールを作成します。以下のコードをコピーし、ペーストしてAmazon SNS クライアントオブジェクトを作成します。REGION(地域)を、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({});

このサンプルコードは、このGitHubにで見つけられます。

unsubscribe.jsというファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

サブスクリプションを解除するAmazon リソースネーム(ARN)を指定して、SubscriptionArn パラメータを含むオブジェクトを作成します。UnsubscribeCommand クライアントクラスの SNS メソッドにパラメータを渡します。

UnsubscribeCommand メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

注記

TOPIC_SUBSCRIPTION_ARN をサブスクリプションを解除するAmazon リソースネーム(ARN)に置き換えてください。

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; };

この例を実行するには、コマンドプロンプトで以下を入力します。

node unsubscribe.js

このサンプルコードは、このGitHubにで見つけられます。