

 [适用于 JavaScript 的 AWS SDK V3 API 参考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)详细描述了 适用于 JavaScript 的 AWS SDK 版本 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/zh_cn/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 模块使用的 SDK JavaScript ，通过`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) 来 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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

创建文件名为 `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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/create-topic.js)示例代码 GitHub。

## 列出主题
<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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

创建文件名为 `list-topics.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建一个空对象以传递到 `SNS` 客户端类的 `ListTopicsCommand` 方法。要调用 `ListTopicsCommand` 方法，请创建一个用于调用 Amazon SNS 服务对象的异步函数并传递参数对象。`data`返回的内容包含您的主题 Amazon 资源名称 (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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-topics.js)示例代码 GitHub。

## 删除主题
<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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

创建文件名为 `delete-topic.js` 的 Node.js 模块。如前所示配置 SDK，包括安装所需的客户端和软件包。

创建包含要删除的主题的 `TopicArn` 的对象，将其传递到 `SNS` 客户端类的 `DeleteTopicCommand` 方法。要调用 `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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/delete-topic.js)示例代码 GitHub。

## 获取主题属性
<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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

创建文件名为 `get-topic-attributes.js` 的 Node.js 模块。按前面所示配置 SDK。

创建包含要删除主题的 `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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-topic-attributes.js)示例代码 GitHub。

## 设置主题属性
<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({});
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/libs/snsClient.js)示例代码 GitHub。

创建文件名为 `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
```

可以在此[处找到此](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-topic-attributes.js)示例代码 GitHub。