Administración de temas en Amazon SNS - AWS SDK para JavaScript

La Guía de referencia de la API de AWS SDK for JavaScript V3 describe en detalle todas las operaciones de la API para la versión 3 (V3) de AWS SDK for JavaScript.

Administración de temas en Amazon SNS

JavaScript code example that applies to Node.js execution

Este ejemplo de código de Node.js muestra:

  • Cómo crear temas en Amazon SNS en los que pueda publicar notificaciones.

  • Cómo eliminar temas creados en Amazon SNS.

  • Cómo obtener una lista de los temas disponibles.

  • Cómo obtener y establecer atributos de temas.

El escenario

En este ejemplo, va a utilizar una serie de módulos de Node.js para crear, enumerar y eliminar temas de Amazon SNS y para gestionar atributos de los temas. Los módulos de Node.js usan el SDK para JavaScript para administrar temas mediante los métodos de clase de cliente de Amazon SNS siguientes:

Tareas previas necesarias

Para configurar y ejecutar este ejemplo, primero debe completar estas tareas:

  • Configure el entorno del proyecto para ejecutar estos ejemplos de Node TypeScript e instale los módulos necesarios de AWS SDK for JavaScript y de terceros. Siga las instrucciones en GitHub.

  • Cree un archivo de configuraciones compartidas con sus credenciales de usuario. Para obtener más información sobre proporcionar un archivo de credenciales compartido, consulte Archivos de configuración y credenciales compartidos en la Guía de referencia de las herramientas y los SDK de AWS.

importante

Estos ejemplos muestran cómo importar/exportar comandos y objetos del servicio de cliente mediante ECMAScript6 (ES6).

Creación de un tema

En este ejemplo, utilice un módulo de Node.js para crear un tema de Amazon SNS.

Cree un directorio libs y un módulo Node.js con el nombre de archivo snsClient.js. Copie y pegue el siguiente código en él, para crear el objeto de cliente de Amazon SNS. Sustituya REGION por su región de 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({});

Este código de ejemplo se puede encontrar aquí en GitHub.

Cree un módulo de Node.js con el nombre de archivo create-topic.js. Configure el SDK como se mostró anteriormente, incluida la instalación de los clientes y paquetes necesarios.

Cree un objeto para transferir el Name del nuevo tema al método CreateTopicCommand de la clase de cliente de Amazon SNS. Para llamar al método CreateTopicCommand, cree una función asincrónica para invocar un objeto de servicio de Amazon SNS mediante el traspaso del objeto de parámetros. Los data devueltos contienen el ARN del tema.

nota

Reemplace TOPIC_NAME por el nombre del tema.

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

Para ejecutar el ejemplo, escriba lo siguiente en la línea de comandos.

node create-topic.js

Este código de ejemplo se puede encontrar aquí en GitHub.

Generación de una lista de sus temas

En este ejemplo, utilice un módulo de Node.js para generar una lista de todos los temas de Amazon SNS.

Cree un directorio libs y un módulo Node.js con el nombre de archivo snsClient.js. Copie y pegue el siguiente código en él, para crear el objeto de cliente de Amazon SNS. Sustituya REGION por su región de 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({});

Este código de ejemplo se puede encontrar aquí en GitHub.

Cree un módulo de Node.js con el nombre de archivo list-topics.js. Configure el SDK como se mostró anteriormente, incluida la instalación de los clientes y paquetes necesarios.

Cree un objeto vacío para transferirlo al método ListTopicsCommand de la clase de cliente de Amazon SNS. Para llamar al método ListTopicsCommand, cree una función asincrónica para invocar un objeto de servicio de Amazon SNS mediante el traspaso del objeto de parámetros. Los data devueltos contienen una matriz de Nombres de recursos de Amazon (ARN) de su tema.

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

Para ejecutar el ejemplo, escriba lo siguiente en la línea de comandos.

node list-topics.js

Este código de ejemplo se puede encontrar aquí en GitHub.

Eliminación de un tema

En este ejemplo, utilice un módulo de Node.js para eliminar un tema de Amazon SNS.

Cree un directorio libs y un módulo Node.js con el nombre de archivo snsClient.js. Copie y pegue el siguiente código en él, para crear el objeto de cliente de Amazon SNS. Sustituya REGION por su región de 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({});

Este código de ejemplo se puede encontrar aquí en GitHub.

Cree un módulo de Node.js con el nombre de archivo delete-topic.js. Configure el SDK como se mostró anteriormente, incluida la instalación de los clientes y paquetes necesarios.

Cree un objeto que contenga el TopicArn del tema que se va a eliminar para transferirlo al método DeleteTopicCommand de la clase de cliente Amazon SNS. Para llamar al método DeleteTopicCommand, cree una función asincrónica para invocar un objeto de servicio de Amazon SNS mediante el traspaso del objeto de parámetros.

nota

Reemplace TOPIC_ARN por el Nombre de recurso de Amazon (ARN) del tema que va a eliminar.

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

Para ejecutar el ejemplo, escriba lo siguiente en la línea de comandos.

node delete-topic.js

Este código de ejemplo se puede encontrar aquí en GitHub.

Obtención de atributos de temas

En este ejemplo, utilice un módulo de Node.js para recuperar atributos de un tema de Amazon SNS.

Cree un directorio libs y un módulo Node.js con el nombre de archivo snsClient.js. Copie y pegue el siguiente código en él, para crear el objeto de cliente de Amazon SNS. Sustituya REGION por su región de 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({});

Este código de ejemplo se puede encontrar aquí en GitHub.

Cree un módulo de Node.js con el nombre de archivo get-topic-attributes.js. Configure el SDK como le hemos mostrado anteriormente.

Cree un objeto que contenga el TopicArn de un tema que se vaya a eliminar para transferirlo al método GetTopicAttributesCommand de la clase de cliente de Amazon SNS. Para llamar al método GetTopicAttributesCommand, invoque un objeto de servicio de cliente de Amazon SNS, mediante el traspaso del objeto de parámetros.

nota

Sustituya TOPIC_ARN por el ARN del tema.

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

Para ejecutar el ejemplo, escriba lo siguiente en la línea de comandos.

node get-topic-attributes.js

Este código de ejemplo se puede encontrar aquí en GitHub.

Configuración de los atributos de un tema

En este ejemplo, utilice un módulo de Node.js para establecer los atributos mutables de un tema de Amazon SNS.

Cree un directorio libs y un módulo Node.js con el nombre de archivo snsClient.js. Copie y pegue el siguiente código en él, para crear el objeto de cliente de Amazon SNS. Sustituya REGION por su región de 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({});

Este código de ejemplo se puede encontrar aquí en GitHub.

Cree un módulo de Node.js con el nombre de archivo set-topic-attributes.js. Configure el SDK como le hemos mostrado anteriormente.

Cree un objeto que contenga los parámetros para realizar la actualización del atributo, como el TopicArn del tema cuyos atributos desea establecer, el nombre del atributo que se va a establecer y el nuevo valor para dicho atributo. Solo puede establecer los atributos Policy, DisplayName y DeliveryPolicy. Transfiera los parámetros al método SetTopicAttributesCommand de la clase de cliente de Amazon SNS. Para llamar al método SetTopicAttributesCommand, cree una función asincrónica para invocar un objeto de servicio de Amazon SNS mediante el traspaso del objeto de parámetros.

nota

Sustituya ATTRIBUTE_NAME por el nombre del atributo que está configurando, TOPIC_ARN por el Nombre de recurso de Amazon (ARN) del tema cuyos atributos desee establecer y NEW_ATTRIBUTE_VALUE por el nuevo valor de ese atributo.

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

Para ejecutar el ejemplo, escriba lo siguiente en la línea de comandos.

node set-topic-attributes.js

Este código de ejemplo se puede encontrar aquí en GitHub.