

 [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-managing-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 でトピックを作成する方法。
+ Amazon SNS で作成されたトピックを削除する方法。
+ 利用可能なトピックの一覧を取得する方法。
+ トピック属性を取得および設定する方法。

## シナリオ
<a name="sns-examples-managing-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/CreateTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CreateTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListTopicsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/DeleteTopicCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetTopicAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetTopicAttributesCommand/)

## 前提条件タスク
<a name="sns-examples-managing-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-managing-topics-createtopic"></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)で見つけられます。

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

`SNS` クライアントクラスの `CreateTopicCommand` メソッドに新しいトピックの `Name` を渡すためのオブジェクトを作成します。`CreateTopicCommand`メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。返された`data`には、トピックの ARN が含まれています。

**注記**  
*TOPIC\$1NAME*は、SNS トピックの名前に置換してください。

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

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

```
node create-topic.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/create-topic.js)で見つけられます。

## トピックの一覧表示
<a name="sns-examples-managing-topics-listtopics"></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-topics.js`というファイル名で Node.js モジュールを作成します。必要なクライアントとパッケージのインストールを含め、前述のようにSDKを設定します。

`SNS` クライアントクラスの `ListTopicsCommand` メソッドに渡す空のオブジェクトを作成します。`ListTopicsCommand`メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。返信された`data`には、トピックの Amazon リソースネーム (ARN)の配列が含まれています。

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

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

```
node list-topics.js
```

 このサンプルコードは、[このGitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-topics.js)にあります。

## トピックの削除
<a name="sns-examples-managing-topics-deletetopic"></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)で見つけられます。

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

`SNS` クライアントクラスの `DeleteTopicCommand` メソッドに渡すために、削除するトピックの `TopicArn` を含むオブジェクトを作成します。`DeleteTopicCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
*[ TOPIC\$1ARN ]*を削除するトピックの Amazon リソースネーム (ARN)に置換してください。

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

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

```
node delete-topic.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/delete-topic.js)で見つけられます。

## トピック属性の取得
<a name="sns-examples-managing-topicsgettopicattributes"></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)で見つけられます。

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

`SNS` クライアントクラスの `GetTopicAttributesCommand` メソッドに渡すために、削除するトピックの `TopicArn` を含むオブジェクトを作成します。`GetTopicAttributesCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
返された*[ TOPIC\$1ARN ]*をトピックのARN に置換してください。

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

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

```
node get-topic-attributes.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-topic-attributes.js)で見つけられます。

## トピック属性の設定
<a name="sns-examples-managing-topicssttopicattributes"></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)で見つけられます。

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

属性を設定するトピックの `TopicArn`、設定する属性の名前、およびその属性の新しい値など、属性の更新のパラメータを含むオブジェクトを作成します。`Policy`、`DisplayName`、および `DeliveryPolicy` 属性のみ設定できます。`SNS` クライアントクラスの `SetTopicAttributesCommand` メソッドにパラメータを渡します。`SetTopicAttributesCommand` メソッドを呼び出すには、Amazon SNS サービスオブジェクトを起動する非同期機能 を作成し、パラメータオブジェクトを渡します。

**注記**  
*ATTRIBUTE\$1NAME* を設定している属性の名前で、*TOPIC\$1ARN* 設定したい属性のトピックの Amazon リソースネーム (ARN)で、 *NEW\$1ATTRIBUTE\$1VALUE* を属性の新しい値に置き換えてください。

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

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

```
node set-topic-attributes.js
```

このサンプルコードは、[このGitHubに](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-topic-attributes.js)で見つけられます。