

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (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/zh_tw/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 模組使用適用於 JavaScript 的 SDK 來管理使用下列`SNS`用戶端類別方法的主題：
+ [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 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

**重要**  
這些範例示範如何使用 ECMAScript6 (ES6) 匯入/匯出用戶端服務物件和命令。  
這需要 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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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，包括安裝所需的用戶端和套件。

建立一個物件，藉此將新主題的 `Name` 傳遞至 `SNS` 用戶端類別的 `CreateTopicCommand` 方法。若要呼叫 `CreateTopicCommand`方法，請建立叫用 Amazon SNS 服務物件、傳遞參數物件的非同步函數。`data` 傳回的 包含主題的 ARN。

**注意**  
將 *TOPIC\$1NAME* 取代為主題的名稱。

```
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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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 Resource Name (ARNs) 的陣列。

```
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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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，包括安裝所需的用戶端和套件。

建立包含欲刪除主題 `TopicArn` 的物件，並將其傳遞至 `SNS` 用戶端類別的 `DeleteTopicCommand` 方法。若要呼叫 `DeleteTopicCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *TOPIC\$1ARN* 取代為您要刪除之主題的 Amazon Resource Name (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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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 模組。依前述內容設定軟體開發套件。

建立包含欲刪除主題 `TopicArn` 的物件，並將其傳遞至 `SNS` 用戶端類別的 `GetTopicAttributesCommand` 方法。若要呼叫 `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`目錄，並建立檔案名稱為 的 Node.js 模組`snsClient.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 模組。依前述內容設定軟體開發套件。

建立一個物件，其中包含用來更新屬性的參數，包括要設定屬性的主題 `TopicArn`、要設定的屬性名稱，以及該屬性的新數值。您只能設定 `Policy`、`DisplayName` 和 `DeliveryPolicy` 屬性。接著，將參數傳遞至 `SNS` 用戶端類別的 `SetTopicAttributesCommand` 方法。若要呼叫 `SetTopicAttributesCommand`方法，請建立叫用 Amazon SNS 用戶端服務物件、傳遞參數物件的非同步函數。

**注意**  
將 *ATTRIBUTE\$1NAME* 取代為您設定的屬性名稱、將 *TOPIC\$1ARN* 取代為您要設定屬性之主題的 Amazon Resource Name (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)範例程式碼。