

 [AWS SDK for JavaScript V3 API リファレンスガイド](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)では、 AWS SDK for JavaScript バージョン3 (V3) のすべての API オペレーションについて詳しく説明します。

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

# Amazon SNS でのサブスクリプションの管理
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

![JavaScript code example that applies to Node.js execution](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/nodeicon.png)

**この Node.js コード例は以下を示しています。**
+ Amazon SNS トピックへのすべてのサブスクリプションを一覧表示する方法。
+ E メールアドレス、アプリケーションエンドポイント、または AWS Lambda 関数を Amazon SNS トピックにサブスクライブする方法。
+ Amazon SNS トピックのサブスクライブを解除する方法。

## シナリオ
<a name="sns-examples-subscribing-unsubscribing-topics-scenario"></a>

この例では、一連の Node.js モジュールを使用して通知メッセージを Amazon SNS トピックに発行します。Node.js モジュールは、`SNS` クライアントクラスの以下のメソッドを使用してトピックを管理するために SDK for JavaScript を使用します。
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListSubscriptionsByTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SubscribeCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ConfirmSubscriptionCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/UnsubscribeCommand/)

## 前提条件タスク
<a name="sns-examples-subscribing-unsubscribing-topics-prerequisites"></a>

この例をセットアップして実行するには、まず次のタスクを完了する必要があります。
+ これらの Node TypeScript の例を実行するようにプロジェクト環境を設定し、必要な AWS SDK for JavaScript モジュールとサードパーティーモジュールをインストールします。「[GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)」の指示に従います。　
+ ユーザーの認証情報を使用して、共有設定ファイルを作成します。共有認証情報ファイルの提供の詳細については、「*AWS SDK とツールのリファレンスガイド*」の「[共有設定ファイルおよび認証情報ファイル](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)」を参照してください。

**重要**  
これらの例は、ECMAScript6 (ES6) を使用してクライアントサービスオブジェクトとコマンドをimport/export する方法を示します。  
これには Node.js バージョン13.x以降が必要です。Node.js の最新バージョンをダウンロードしてインストールするには、「[Node.js ダウンロード](https://nodejs.org/en/download)」を参照してください。
CommonJS 構文を使用する場合は、「[JavaScript ES6/CommonJS 構文](sdk-example-javascript-syntax.md)」を参照してください。

## サブスクリプションのトピックへの一覧表示
<a name="sns-examples-list-subscriptions-email"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

サブスクリプションを一覧表示するトピックの `TopicArn` パラメータを含むオブジェクトを作成します。`SNS` クライアントクラスの `ListSubscriptionsByTopicCommand` メソッドにパラメータを渡します。`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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-subscriptions-by-topic.js)で見つけられます。

## E メールアドレスのトピックへのサブスクライブ
<a name="sns-examples-subscribing-email"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

`email` プロトコル、サブスクライブするトピックの `TopicArn`、およびメッセージの `Endpoint` としての E メールアドレスを指定するための `Protocol` パラメータを含むオブジェクトを作成します。`SNS` クライアントクラスの `SubscribeCommand` メソッドにパラメータを渡します。このトピックの他の例が示すように、渡されたパラメータに使用される値に応じて、`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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-email.js)で見つけられます。

### サブスクリプションを確認する
<a name="sns-confirm-subscription-email"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

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

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

![SNS トピックにサブスクライブしている E メールアドレスを示すサブスクリプション確認メッセージ。](http://docs.aws.amazon.com/ja_jp/sdk-for-javascript/v3/developer-guide/images/token.png)


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

**注記**  
{{TOPIC\_ARN}}をトピックの Amazon リソースネーム (ARN)に、{{TOKEN}}を以前の`Subscribe`アクションでエンドポイント所有者に送信されたURLのトークン値に置き換えてください。そして、定義{{AuthenticateOnUnsubscribe}}を`TRUE`か`FALSE`の値で定義します。

```
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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/confirm-subscription.js)で見つけられます。

## アプリケーションエンドポイントのトピックへのサブスクライブ
<a name="sns-examples-subscribing-apps"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

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

`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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-app.js)で見つけられます。

## Lambda 関数のトピックへのサブスクライブ
<a name="sns-examples-subscribing-lambda"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

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

`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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/subscribe-lambda.js)で見つけられます。

## トピックからのサブスクリプションの解除
<a name="sns-examples-unsubscribing"></a>

この例では、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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)で見つけられます。

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

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

`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に](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/unsubscribe.js)で見つけられます。