

 [AWS SDK for JavaScript V3 API 참조 안내서](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)는 AWS SDK for JavaScript 버전 3(V3)의 모든 API 작업을 자세히 설명합니다.

기계 번역으로 제공되는 번역입니다. 제공된 번역과 원본 영어의 내용이 상충하는 경우에는 영어 버전이 우선합니다.

# Amazon Simple Notification Service 예
<a name="sns-examples"></a>

Amazon Simple Notification Service(Amazon SNS)는 구독 엔드포인트 또는 클라이언트에 대한 메시지 전송 또는 전송을 조정하고 관리하는 웹 서비스입니다.

Amazon SNS에는 게시자와 구독자 또는 생산자와 소비자라고 하는 두 가지 클라이언트 유형이 있습니다.

![\[JavaScript 환경, SDK, Amazon SNS 간의 관계\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/code-samples-sns.png)


게시자는 주제에 대한 메시지를 생산 및 발송함으로써 구독자와 비동시적으로 통신하는 논리적 액세스 및 커뮤니케이션 채널입니다. 구독자(웹 서버, 이메일 주소, Amazon SQS 대기열, AWS Lambda 함수)는 주제를 구독할 때 지원되는 프로토콜(Amazon SQS, HTTP/S, 이메일, SMS AWS Lambda) 중 하나를 통해 메시지 또는 알림을 소비하거나 수신합니다.

Amazon SNS용 JavaScript API는 [Class: SNS](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SNS/)를 통해 노출됩니다.

**Topics**
+ [Amazon SNS에서 주제 관리](sns-examples-managing-topics.md)
+ [Amazon SNS에서 메시지 게시](sns-examples-publishing-messages.md)
+ [Amazon SNS에서 구독 관리](sns-examples-subscribing-unsubscribing-topics.md)
+ [Amazon SNS를 통한 SMS 메시지 전송](sns-examples-sending-sms.md)

# Amazon SNS에서 주제 관리
<a name="sns-examples-managing-topics"></a>

![\[JavaScript code example that applies to Node.js execution\]](http://docs.aws.amazon.com/ko_kr/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 for 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>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

**중요**  
이 예는 ECMAScript6(ES6)를 사용하여 클라이언트 서비스 객체 및 명령을 가져오거나 내보내는 방법을 보여줍니다.  
따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](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*을 주제 이름으로 바꿉니다.

```
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) 찾을 수 있습니다.

# Amazon SNS에서 메시지 게시
<a name="sns-examples-publishing-messages"></a>

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

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS 주제에 메시지를 게시하는 방법

## 시나리오
<a name="sns-examples-publishing-messages-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS의 메시지를 주제 엔드포인트, 이메일 또는 전화번호에 게시합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SNS` 클라이언트 클래스의 다음 메서드를 사용하여 메시지를 전송합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 사전 필수 작업
<a name="sns-examples-publishing-messages-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

**중요**  
이 예는 ECMAScript6(ES6)를 사용하여 클라이언트 서비스 객체 및 명령을 가져오거나 내보내는 방법을 보여줍니다.  
따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](https://nodejs.org/en/download)를 참조하세요.
CommonJS 구문을 사용하려는 경우 [JavaScript ES6/CommonJS 구문](sdk-example-javascript-syntax.md) 단원을 참조하세요.

## SNS 주제에 메시지 게시
<a name="sns-examples-publishing-text-messages"></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) 찾을 수 있습니다.

 파일 이름이 `publish-topic.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다.

메시지 텍스트와 Amazon SNS 주제의 Amazon 리소스 이름(ARN)을 비롯하여 메시지 게시를 위한 파라미터가 포함된 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 세부 정보는 [SetSMSAttributes](https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/SNS.html#setSMSAttributes-property)를 참조하세요.

`SNS` 클라이언트 클래스의 `PublishCommand` 메서드에 파라미터를 전달합니다. Amazon SNS 클라이언트 서비스 객체를 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*MESSAGE\$1TEXT*를 메시지 텍스트로 바꾸고, *TOPIC\$1ARN*을 SNS 주제의 ARN으로 바꿉니다.

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {string} topicArn - The ARN of the topic to which you would like to publish.
 */
export const publish = async (
  message = "Hello from SNS!",
  topicArn = "TOPIC_ARN",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      TopicArn: topicArn,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: 'e7f77526-e295-5325-9ee4-281a43ad1f05',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node publish-topic.js
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-topic.js) 찾을 수 있습니다.

# Amazon SNS에서 구독 관리
<a name="sns-examples-subscribing-unsubscribing-topics"></a>

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

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS 주제의 모든 구독을 나열하는 방법
+ 이메일 주소, 애플리케이션 엔드포인트 또는 AWS Lambda 함수에서 Amazon SNS 주제를 구독하는 방법
+ Amazon SNS 주제의 구독을 취소하는 방법

## 시나리오
<a name="sns-examples-subscribing-unsubscribing-topics-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS 주제에 알림 메시지를 게시합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SNS` 클라이언트 클래스의 다음 메서드를 사용하여 주제를 관리합니다.
+ [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>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

**중요**  
이 예는 ECMAScript6(ES6)를 사용하여 클라이언트 서비스 객체 및 명령을 가져오거나 내보내는 방법을 보여줍니다.  
따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](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\$1ARN*을 구독을 나열하려는 주제의 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) 찾을 수 있습니다.

## 이메일 주소에서 주제 구독
<a name="sns-examples-subscribing-email"></a>

이 예에서는 Node.js 모듈을 사용하여 이메일 주소에서 Amazon SNS 주제의 SMTP 이메일 메시지를 수신하도록 이메일 주소에서 주제를 구독합니다.

`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`로 사용되는 이메일 주소를 지정하기 위한 `Protocol` 파라미터를 포함하는 객체를 생성합니다. `SNS` 클라이언트 클래스의 `SubscribeCommand` 메서드에 파라미터를 전달합니다. 이 항목의 다른 예에 나와 있듯이, `subscribe` 메서드를 사용하면 전달된 파라미터에 사용되는 값에 따라 여러 다양한 엔드포인트에서 Amazon SNS 주제를 구독할 수 있습니다.

`SubscribeCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*TOPIC\$1ARN*을 주제의 Amazon 리소스 이름(ARN)으로 바꾸고, *EMAIL\$1ADDRESS*를 구독할 이메일 주소로 바꿉니다.

```
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 모듈을 사용하여 이전 구독 작업에서 엔드포인트로 전송한 토큰을 검증함으로써 엔드포인트 소유자의 이메일 수신 의도를 확인합니다.

`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`은 이메일 소유자에게 전송된 구독 확인 이메일의 URL에 있습니다. 예를 들어 `abc123`은 다음 URL의 토큰입니다.

![\[Amazon Web Services Simple Notification Service subscription confirmation page.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/token.png)


`ConfirmSubscriptionCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*TOPIC\$1ARN*을 주제의 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를 구성합니다.

`Protocol` 파라미터가 포함된 객체를 생성하여 `application` 프로토콜, 구독할 주제의 `TopicArn`, `Endpoint` 파라미터에 대한 모바일 애플리케이션 엔드포인트의 Amazon 리소스 이름(ARN)을 지정합니다. `SNS` 클라이언트 클래스의 `SubscribeCommand` 메서드에 파라미터를 전달합니다.

`SubscribeCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*TOPIC\$1ARN*을 주제의 Amazon 리소스 이름(ARN)으로 바꾸고, *MOBILE\$1ENDPOINT\$1ARN*을 주제를 구독하는 엔드포인트로 바꿉니다.

```
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 모듈을 사용하여 Amazon SNS 주제에서 알림을 수신하도록 AWS Lambda 함수를 구독합니다.

`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\$1ARN*을 주제의 Amazon 리소스 이름(ARN)으로 바꾸고, *LAMBDA\$1FUNCTION\$1ARN*을 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를 구성합니다.

`SubscriptionArn` 파라미터가 포함된 객체를 생성하여 취소할 구독의 Amazon 리소스 이름(ARN)을 지정합니다. `SNS` 클라이언트 클래스의 `UnsubscribeCommand` 메서드에 파라미터를 전달합니다.

`UnsubscribeCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*TOPIC\$1SUBSCRIPTION\$1ARN*을 취소할 구독의 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) 찾을 수 있습니다.

# Amazon SNS를 통한 SMS 메시지 전송
<a name="sns-examples-sending-sms"></a>

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

**이 Node.js 코드 예제는 다음을 보여 줍니다.**
+ Amazon SNS에 대한 SMS 메시징 기본 설정을 가져오고 설정하는 방법
+ 전화번호를 점검하여 SMS 메시지 수신을 옵트아웃했는지 여부를 확인하는 방법.
+ SMS 메시지 수신을 옵트아웃한 전화번호의 목록을 가져오는 방법.
+ SMS 메시지를 전송하는 방법.

## 시나리오
<a name="sns-examples-sending-sms-scenario"></a>

사용자는 Amazon SNS를 사용하여 SMS 수신 가능한 디바이스에 문자 메시지 또는 SMS 메시지를 전송할 수 있습니다. 전화번호로 메시지를 직접 전송할 수 있으며, 전화번호에서 주제를 구독하고 메시지를 주제로 전송하여 메시지를 여러 전화번호로 한 번에 전송할 수 있습니다.

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SNS의 SMS 문자 메시지를 SMS 지원 디바이스에 게시합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SNS` 클라이언트 클래스의 다음 메서드를 사용하여 SMS 메시지를 게시합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/GetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/SetSMSAttributesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/CheckIfPhoneNumberIsOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/ListPhoneNumbersOptedOutCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-sns/Class/PublishCommand/)

## 사전 필수 작업
<a name="sns-examples-sending-sms-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.

**중요**  
이 예는 ECMAScript6(ES6)를 사용하여 클라이언트 서비스 객체 및 명령을 가져오거나 내보내는 방법을 보여줍니다.  
따라서 Node.js 버전 13.x 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](https://nodejs.org/en/download)를 참조하세요.
CommonJS 구문을 사용하려는 경우 [JavaScript ES6/CommonJS 구문](sdk-example-javascript-syntax.md) 단원을 참조하세요.

## SMS 속성 가져오기
<a name="sending-sms-getattributes"></a>

Amazon SNS를 사용하여 전송을 최적화하는 방법(비용 또는 안정성 있는 전송), 월 지출 한도, 메시지 전송을 로깅하는 방법, 일일 SMS 사용 보고서를 구독하는지 여부 등 SMS 메시징에 대한 기본 설정을 지정합니다. 이러한 기본 설정을 검색하여 Amazon SNS의 SMS 속성으로 설정합니다.

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS에서 현재 SMS 속성을 가져옵니다.

`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-sms-attributes.js`인 Node.js 모듈을 생성합니다.

필수 클라이언트 및 패키지 다운로드를 포함하여 앞서 나와 있는 것처럼 SDK를 구성합니다. 가져올 개별 속성의 이름을 포함하여 SMS 속성을 가져오기 위한 파라미터를 포함하는 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 자세한 내용은 Amazon Simple Notification Service API 참조의 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)를 참조하세요.

이 예제에서는 SMS 메시지를 최저 비용이 발생하도록 메시지 전송을 최적화하는 `Promotional`로 전송할지 또는 최고 안정성을 달성하도록 메시지 전송을 최적화하는 `Transactional`로 전송할지를 제어하는 `DefaultSMSType` 속성을 가져옵니다. `SNS` 클라이언트 클래스의 `SetTopicAttributesCommand` 메서드에 파라미터를 전달합니다. `SetSMSAttributesCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*ATTRIBUTE\$1NAME*을 속성 이름으로 바꿉니다.

```
import { GetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const getSmsAttributes = async () => {
  const response = await snsClient.send(
    // If you have not modified the account-level mobile settings of SNS,
    // the DefaultSMSType is undefined. For this example, it was set to
    // Transactional.
    new GetSMSAttributesCommand({ attributes: ["DefaultSMSType"] }),
  );

  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '67ad8386-4169-58f1-bdb9-debd281d48d5',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   attributes: { DefaultSMSType: 'Transactional' }
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node get-sms-attributes.js
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/get-sms-attributes.js) 찾을 수 있습니다.

## SMS 속성 설정
<a name="sending-sms-setattributes"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SNS에서 현재 SMS 속성을 가져옵니다.

`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-sms-attribute-type.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성합니다. 설정할 개별 속성의 이름과 각 속성에 설정할 값을 포함하여 SMS 속성을 설정하기 위한 파라미터를 포함하는 객체를 생성합니다. 사용 가능한 SMS 속성에 대한 자세한 내용은 Amazon Simple Notification Service API 참조의 [SetSMSAttributes](https://docs.aws.amazon.com/sns/latest/api/API_SetSMSAttributes.html)를 참조하세요.

다음 예제에서는 `DefaultSMSType` 속성을 `Transactional`로 설정하여 최고의 안정성을 달성하도록 메시지 전송을 최적화합니다. `SNS` 클라이언트 클래스의 `SetTopicAttributesCommand` 메서드에 파라미터를 전달합니다. `SetSMSAttributesCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

```
import { SetSMSAttributesCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {"Transactional" | "Promotional"} defaultSmsType
 */
export const setSmsType = async (defaultSmsType = "Transactional") => {
  const response = await snsClient.send(
    new SetSMSAttributesCommand({
      attributes: {
        // Promotional – (Default) Noncritical messages, such as marketing messages.
        // Transactional – Critical messages that support customer transactions,
        // such as one-time passcodes for multi-factor authentication.
        DefaultSMSType: defaultSmsType,
      },
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '1885b977-2d7e-535e-8214-e44be727e265',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   }
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node set-sms-attribute-type.js 
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/set-sms-attribute-type.js) 찾을 수 있습니다.

## 전화번호가 옵트아웃되었는지 여부 확인
<a name="sending-sms-checkifphonenumberisoptedout"></a>

이 예제에서는 Node.js 모듈을 사용하여 전화 번호가 SMS 메시지 수신에서 옵트아웃되었는지 여부를 확인합니다.

`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) 찾을 수 있습니다.

파일 이름이 `check-if-phone-number-is-opted-out.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 파라미터로 확인할 전화번호를 포함하는 객체를 생성합니다.

이 예제에서는 확인할 전화번호를 지정하는 `PhoneNumber` 파라미터를 설정합니다. `SNS` 클라이언트 클래스의 `CheckIfPhoneNumberIsOptedOutCommand` 메서드에 객체를 전달합니다. `CheckIfPhoneNumberIsOptedOutCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  

*PHONE\$1NUMBER*를 전화번호로 바꿉니다.

```
import { CheckIfPhoneNumberIsOptedOutCommand } from "@aws-sdk/client-sns";

import { snsClient } from "../libs/snsClient.js";

export const checkIfPhoneNumberIsOptedOut = async (
  phoneNumber = "5555555555",
) => {
  const command = new CheckIfPhoneNumberIsOptedOutCommand({
    phoneNumber,
  });

  const response = await snsClient.send(command);
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '3341c28a-cdc8-5b39-a3ee-9fb0ee125732',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   isOptedOut: false
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node check-if-phone-number-is-opted-out.js 
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/check-if-phone-number-is-opted-out.js) 찾을 수 있습니다.

## 옵트아웃된 전화번호 나열
<a name="sending-sms-listphonenumbersoptedout"></a>

이 예제에서는 Node.js 모듈을 사용하여 SMS 메시지 수신에서 옵트아웃한 전화번호의 목록을 가져옵니다.

`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-phone-numbers-opted-out.js`인 Node.js 모듈을 생성합니다. 위와 같이 SDK를 구성합니다. 비어 있는 객체를 파라미터로 생성합니다.

`SNS` 클라이언트 클래스의 `ListPhoneNumbersOptedOutCommand` 메서드에 객체를 전달합니다. `ListPhoneNumbersOptedOutCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 클라이언트 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

```
import { ListPhoneNumbersOptedOutCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

export const listPhoneNumbersOptedOut = async () => {
  const response = await snsClient.send(
    new ListPhoneNumbersOptedOutCommand({}),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '44ff72fd-1037-5042-ad96-2fc16601df42',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   phoneNumbers: ['+15555550100']
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node list-phone-numbers-opted-out.js 
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/list-phone-numbers-opted-out.js) 찾을 수 있습니다.

## SMS 메시지 게시
<a name="sending-sms-publishsms"></a>

이 예제에서는 Node.js 모듈을 사용하여 SMS 메시지를 전화번호에 전송합니다.

`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) 찾을 수 있습니다.

파일 이름이 `publish-sms.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성합니다. `Message` 및 `PhoneNumber` 파라미터를 포함하는 객체를 생성합니다.

SMS 메시지를 전송할 때 E.164 형식을 사용하여 전화번호를 지정합니다. E.164는 국제 통신에 사용되는 전화번호 구조의 표준입니다. 이 형식을 따르는 전화번호는 최대 15자리 숫자를 사용할 수 있으며 더하기 문자(\$1) 및 국가 코드가 접두사로 추가됩니다. 예를 들어, E.164 형식의 미국 전화번호는 \$11001XXX5550100으로 표시될 수 있습니다.

이 예제에서는 메시지를 전송할 전화번호를 지정하는 `PhoneNumber` 파라미터를 설정합니다. `SNS` 클라이언트 클래스의 `PublishCommand` 메서드에 객체를 전달합니다. `PublishCommand` 메서드를 직접적으로 호출하려면 Amazon SNS 서비스 객체를 간접적으로 호출하는 비동기 함수를 생성하여 파라미터 객체를 전달합니다.

**참고**  
*TEXT\$1MESSAGE*를 텍스트 메시지로 바꾸고, *PHONE\$1NUMBER*를 전화번호로 바꿉니다.

```
import { PublishCommand } from "@aws-sdk/client-sns";
import { snsClient } from "../libs/snsClient.js";

/**
 * @param {string | Record<string, any>} message - The message to send. Can be a plain string or an object
 *                                                 if you are using the `json` `MessageStructure`.
 * @param {*} phoneNumber - The phone number to send the message to.
 */
export const publish = async (
  message = "Hello from SNS!",
  phoneNumber = "+15555555555",
) => {
  const response = await snsClient.send(
    new PublishCommand({
      Message: message,
      // One of PhoneNumber, TopicArn, or TargetArn must be specified.
      PhoneNumber: phoneNumber,
    }),
  );
  console.log(response);
  // {
  //   '$metadata': {
  //     httpStatusCode: 200,
  //     requestId: '7410094f-efc7-5f52-af03-54737569ab77',
  //     extendedRequestId: undefined,
  //     cfId: undefined,
  //     attempts: 1,
  //     totalRetryDelay: 0
  //   },
  //   MessageId: 'xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx'
  // }
  return response;
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다.

```
node publish-sms.js
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/sns/actions/publish-sms.js) 찾을 수 있습니다.