

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

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

# SDK for JavaScript 코드 예
<a name="sdk-code-samples"></a>

이 섹션의 주제에는 다양한 서비스의 API와 AWS SDK for JavaScript 함께를 사용하여 일반적인 작업을 수행하는 방법에 대한 예제가 포함되어 있습니다. APIs 

[GitHub의AWS 코드 예 리포지토리](https://github.com/awsdocs/aws-doc-sdk-examples)에서 이러한 예의 소스 코드와 다른 소스 코드를 찾아보세요. AWS 설명서 팀이 생성을 고려할 새 코드 예제를 제안하려면 요청을 생성합니다. 이 팀은 개별 API 호출만 다루는 간단한 코드 조각에 비해 광범위한 시나리오 및 사용 사례를 다루는 코드를 생성하려고 합니다. 지침은 [GitHub Contributing Guidelines](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/CONTRIBUTING.md)의 *코드 작성* 섹션을 참조하세요.

**중요**  
이러한 예에서는 ECMAScript6 import/export 구문을 사용합니다.  
따라서 Node.js 버전 14.17 이상이 필요합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](https://nodejs.org/en/download)를 참조하세요.
CommonJS 구문을 사용하려는 경우 변환 지침은 [JavaScript ES6/CommonJS 구문](sdk-example-javascript-syntax.md) 단원을 참조하세요.

**Topics**
+ [

# JavaScript ES6/CommonJS 구문
](sdk-example-javascript-syntax.md)
+ [

# AWS Elemental MediaConvert 예제
](emc-examples.md)
+ [

# AWS Lambda 예제
](lambda-examples.md)
+ [

# Amazon Lex 예
](lex-examples.md)
+ [

# Amazon Polly 예
](polly-examples.md)
+ [

# Amazon Redshift 예
](redshift-examples.md)
+ [

# Amazon Simple Email Service 예
](ses-examples.md)
+ [

# Amazon Simple Notification Service 예
](sns-examples.md)
+ [

# Amazon Transcribe 예
](Transcribe-examples.md)
+ [

# Amazon EC2 인스턴스에서 Node.js 설정
](setting-up-node-on-ec2-instance.md)
+ [

# API Gateway를 사용하여 Lambda 호출
](api-gateway-invoking-lambda-example.md)
+ [

# AWS Lambda 함수를 실행하기 위한 예약된 이벤트 생성
](scheduled-events-invoking-lambda-example.md)
+ [

# Amazon Lex 챗봇 빌드
](lex-bot-example.md)

# JavaScript ES6/CommonJS 구문
<a name="sdk-example-javascript-syntax"></a>

AWS SDK for JavaScript 코드 예는 ECMAScript 6(ES6)로 작성되었습니다. ES6는 코드를 더 현대적이고 읽기 쉽게 만들고 더 많은 작업을 수행할 수 있도록 새로운 구문과 새로운 기능을 제공합니다.

ES6에서는 Node.js 버전 13.x 이상을 사용해야 합니다. 최신 버전의 Node.js를 다운로드하여 설치하려면 [Node.js downloads](https://nodejs.org/en/download)를 참조하세요. 그러나 원하는 경우 다음 지침을 사용하여 코드 예를 CommonJS 구문으로 변환할 수 있습니다.
+ 프로젝트 환경의 `package.json`에서 `"type" : "module"`을 제거합니다.
+ 모든 ES6 `import` 문을 CommonJS `require` 문으로 변환합니다. 예를 들어 다음과 같이 변환합니다.

  ```
  import { CreateBucketCommand } from "@aws-sdk/client-s3";
  import { s3 } from "./libs/s3Client.js";
  ```

  위 구문을 동등한 다음 CommonJS 문으로 변환합니다.

  ```
  const { CreateBucketCommand } = require("@aws-sdk/client-s3");
  const { s3 } = require("./libs/s3Client.js");
  ```
+ 모든 ES6 `export` 문을 CommonJS `module.exports` 문으로 변환합니다. 예를 들어 다음과 같이 변환합니다.

  ```
  export {s3}
  ```

  위 구문을 동등한 다음 CommonJS 문으로 변환합니다.

  ```
  module.exports = {s3}
  ```

다음 예에서는 ES6와 CommonJS 모두에서 Amazon S3 버킷을 생성하는 코드 예를 보여줍니다.

------
#### [ ES6 ]

libs/s3Client.js

```
// Create service client module using ES6 syntax.
import { S3Client } from "@aws-sdk/client-s3";
// Set the AWS region
const REGION = "eu-west-1"; //e.g. "us-east-1"
// Create Amazon S3 service object.
const s3 = new S3Client({ region: REGION });
// Export 's3' constant.
export {s3};
```

s3\$1createbucket.js

```
// Get service clients module and commands using ES6 syntax.
 import { CreateBucketCommand } from "@aws-sdk/client-s3";
 import { s3 } from "./libs/s3Client.js";

// Get service clients module and commands using CommonJS syntax.
// const { CreateBucketCommand } = require("@aws-sdk/client-s3");
// const { s3 } = require("./libs/s3Client.js");

// Set the bucket parameters
const bucketParams = { Bucket: "BUCKET_NAME" };

// Create the Amazon S3 bucket.
const run = async () => {
  try {
    const data = await s3.send(new CreateBucketCommand(bucketParams));
    console.log("Success", data.Location);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------
#### [ CommonJS ]

libs/s3Client.js

```
// Create service client module using CommonJS syntax.
 const { S3Client } = require("@aws-sdk/client-s3");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
 // Create Amazon S3 service object.
const s3 = new S3Client({ region: REGION });
// Export 's3' constant.
 module.exports ={s3};
```

s3\$1createbucket.js

```
// Get service clients module and commands using CommonJS syntax.
const { CreateBucketCommand } = require("@aws-sdk/client-s3");
const { s3 } = require("./libs/s3Client.js");

// Set the bucket parameters
const bucketParams = { Bucket: "BUCKET_NAME" };

// Create the Amazon S3 bucket.
const run = async () => {
  try {
    const data = await s3.send(new CreateBucketCommand(bucketParams));
    console.log("Success", data.Location);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

------

# AWS Elemental MediaConvert 예제
<a name="emc-examples"></a>

AWS Elemental MediaConvert는 브로드캐스트급 기능을 갖춘 파일 기반의 비디오 트랜스코딩 서비스입니다. 이 서비스를 사용하여 인터넷에서 브로드캐스트 및 비디오 온디맨드(VOD) 전달용 자산을 생성할 수 있습니다. 자세한 설명은 [https://docs.aws.amazon.com/mediaconvert/latest/ug/](https://docs.aws.amazon.com/mediaconvert/latest/ug/)를 참조하세요.

MediaConvert용 JavaScript API는 `MediaConvert` 클라이언트 클래스를 통해 노출됩니다. 자세한 내용은 API 참조의 [Class: MediaConvert](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/)를 참조하세요.

**Topics**
+ [

# MediaConvert에서 트랜스코딩 작업 생성 및 관리
](emc-examples-jobs.md)
+ [

# MediaConvert에서 작업 템플릿 사용
](emc-examples-templates.md)

# MediaConvert에서 트랜스코딩 작업 생성 및 관리
<a name="emc-examples-jobs"></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 코드 예제는 다음을 보여 줍니다.**
+ MediaConvert에서 트랜스코딩 작업을 생성하는 방법
+ 트랜스코딩 작업을 취소하는 방법.
+ 완료된 트랜스코딩 작업에 대한 JSON을 검색하는 방법.
+ 최근에 생성된 최대 20개 작업에 대한 JSON 배열을 검색하는 방법.

## 시나리오
<a name="emc-examples-jobs-scenario"></a>

이 예에서는 Node.js 모듈을 사용하여 트랜스코딩 작업을 생성하고 관리할 MediaConvert를 직접적으로 호출합니다. 이 코드는 SDK for JavaScript에서 MediaConvert 클라이언트 클래스의 다음 메서드를 사용하여 이 작업을 수행합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CancelJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CancelJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/GetJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/GetJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobsCommand/)

## 사전 필수 작업
<a name="emc-examples-jobs-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ 이러한 노드 TypeScript 예를 실행하도록 프로젝트 환경을 설정하고 필수 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/mediaconvert/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.
+ 작업 입력 파일 및 출력 파일을 위한 스토리지를 제공하는 Amazon S3 버킷을 생성하고 구성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [Create storage for files](https://docs.aws.amazon.com/mediaconvert/latest/ug/set-up-file-locations.html) 단원을 참조하세요.
+ 입력 스토리지를 위해 프로비저닝한 Amazon S3 버킷에 입력 비디오를 업로드합니다. 지원되는 입력 비디오 코덱 및 컨테이너 목록은 *AWS Elemental MediaConvert 사용 설명서*의 [Supported input codecs and containers](https://docs.aws.amazon.com/mediaconvert/latest/ug/reference-codecs-containers-input.html) 단원을 참조하세요.
+ 출력 파일이 저장된 Amazon S3 버킷 및 입력 파일에 대한 액세스 권한을 MediaConvert에 부여하는 IAM 역할을 생성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [Set up IAM permissions](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.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="emc-examples-jobs-spec"></a>

파일 이름이 `emc_createjob.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 트랜스코드 작업 파라미터를 정의하는 JSON을 생성합니다.

이러한 파라미터는 매우 세부적입니다. [AWS Elemental MediaConvert 콘솔](https://console.aws.amazon.com/mediaconvert/)을 사용하면 콘솔에서 작업 설정을 선택한 다음, **작업** 섹션 하단에서 **작업 JSON 표시**를 선택하여 JSON 작업 파라미터를 생성할 수 있습니다. 이 예제는 단순 작업용 JSON을 보여줍니다.

**참고**  
*JOB\$1QUEUE\$1ARN*을 MediaConvert 작업 대기열로 바꾸고, *IAM\$1ROLE\$1ARN*을 IAM 역할의 Amazon 리소스 이름(ARN)으로 바꾸고, *OUTPUT\$1BUCKET\$1NAME*을 대상 버킷 이름(예: "s3://OUTPUT\$1BUCKET\$1NAME/")으로 바꾸고, *INPUT\$1BUCKET\$1AND\$1FILENAME*을 입력 버킷 및 파일 이름(예: "s3://INPUT\$1BUCKET/FILE\$1NAME")으로 바꿉니다.

```
const params = {
  Queue: "JOB_QUEUE_ARN", //JOB_QUEUE_ARN
  UserMetadata: {
    Customer: "Amazon",
  },
  Role: "IAM_ROLE_ARN", //IAM_ROLE_ARN
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "OUTPUT_BUCKET_NAME", //OUTPUT_BUCKET_NAME, e.g., "s3://BUCKET_NAME/"
          },
        },
        Outputs: [
          {
            VideoDescription: {
              ScalingBehavior: "DEFAULT",
              TimecodeInsertion: "DISABLED",
              AntiAlias: "ENABLED",
              Sharpness: 50,
              CodecSettings: {
                Codec: "H_264",
                H264Settings: {
                  InterlaceMode: "PROGRESSIVE",
                  NumberReferenceFrames: 3,
                  Syntax: "DEFAULT",
                  Softness: 0,
                  GopClosedCadence: 1,
                  GopSize: 90,
                  Slices: 1,
                  GopBReference: "DISABLED",
                  SlowPal: "DISABLED",
                  SpatialAdaptiveQuantization: "ENABLED",
                  TemporalAdaptiveQuantization: "ENABLED",
                  FlickerAdaptiveQuantization: "DISABLED",
                  EntropyEncoding: "CABAC",
                  Bitrate: 5000000,
                  FramerateControl: "SPECIFIED",
                  RateControlMode: "CBR",
                  CodecProfile: "MAIN",
                  Telecine: "NONE",
                  MinIInterval: 0,
                  AdaptiveQuantization: "HIGH",
                  CodecLevel: "AUTO",
                  FieldEncoding: "PAFF",
                  SceneChangeDetect: "ENABLED",
                  QualityTuningLevel: "SINGLE_PASS",
                  FramerateConversionAlgorithm: "DUPLICATE_DROP",
                  UnregisteredSeiTimecode: "DISABLED",
                  GopSizeUnits: "FRAMES",
                  ParControl: "SPECIFIED",
                  NumberBFramesBetweenReferenceFrames: 2,
                  RepeatPps: "DISABLED",
                  FramerateNumerator: 30,
                  FramerateDenominator: 1,
                  ParNumerator: 1,
                  ParDenominator: 1,
                },
              },
              AfdSignaling: "NONE",
              DropFrameTimecode: "ENABLED",
              RespondToAfd: "NONE",
              ColorMetadata: "INSERT",
            },
            AudioDescriptions: [
              {
                AudioTypeControl: "FOLLOW_INPUT",
                CodecSettings: {
                  Codec: "AAC",
                  AacSettings: {
                    AudioDescriptionBroadcasterMix: "NORMAL",
                    RateControlMode: "CBR",
                    CodecProfile: "LC",
                    CodingMode: "CODING_MODE_2_0",
                    RawFormat: "NONE",
                    SampleRate: 48000,
                    Specification: "MPEG4",
                    Bitrate: 64000,
                  },
                },
                LanguageCodeControl: "FOLLOW_INPUT",
                AudioSourceName: "Audio Selector 1",
              },
            ],
            ContainerSettings: {
              Container: "MP4",
              Mp4Settings: {
                CslgAtom: "INCLUDE",
                FreeSpaceBox: "EXCLUDE",
                MoovPlacement: "PROGRESSIVE_DOWNLOAD",
              },
            },
            NameModifier: "_1",
          },
        ],
      },
    ],
    AdAvailOffset: 0,
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
        FileInput: "INPUT_BUCKET_AND_FILENAME", //INPUT_BUCKET_AND_FILENAME, e.g., "s3://BUCKET_NAME/FILE_NAME"
      },
    ],
    TimecodeConfig: {
      Source: "EMBEDDED",
    },
  },
};
```

## 트랜스코딩 작업 생성
<a name="emc-examples-jobs-create"></a>

작업 파라미터 JSON을 생성한 후 비동기 `run` 메서드를 직접적으로 호출하여 `MediaConvert` 클라이언트 서비스 객체를 간접적으로 호출해서 파라미터를 전달합니다. 생성된 작업의 ID는 응답 `data`에서 반환됩니다.

```
const run = async () => {
  try {
    const data = await emcClient.send(new CreateJobCommand(params));
    console.log("Job created!", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_createjob.js 
```

이 전체 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/mediaconvert/src/emc_createjob.js) 찾을 수 있습니다.

## 트랜스코딩 작업 취소
<a name="emc-examples-jobs-cancel"></a>

파일 이름이 `emc_canceljob.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 다운로드를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 취소할 작업의 ID가 포함된 JSON을 생성합니다. 그런 다음, 파라미터를 전달하는 `MediaConvert` 클라이언트 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하여 `CancelJobCommand` 메서드를 직접적으로 호출합니다. promise 콜백에서 응답을 처리합니다.

**참고**  
*JOB\$1ID*를 취소할 작업의 ID로 바꿉니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { CancelJobCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = { Id: "JOB_ID" }; //JOB_ID

const run = async () => {
  try {
    const data = await emcClient.send(new CancelJobCommand(params));
    console.log(`Job  ${params.Id} is canceled`);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node ec2_canceljob.js 
```

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

## 최근 트랜스코딩 작업 나열
<a name="emc-examples-jobs-listing"></a>

파일 이름이 `emc_listjobs.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다.

목록을 `ASCENDING` 또는 `DESCENDING` 순서로 정렬할지 여부, 확인할 작업 대기열의 Amazon 리소스 이름(ARN), 포함할 작업의 상태 등을 지정하는 값을 포함하여 파라미터 JSON을 생성합니다. 그런 다음, 파라미터를 전달하는 `MediaConvert` 클라이언트 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하여 `ListJobsCommand` 메서드를 직접적으로 호출합니다.

**참고**  
*QUEUE\$1ARN*을 확인할 작업 대기열의 Amazon 리소스 이름(ARN)으로 바꾸고 *STATUS*를 대기열의 상태로 바꿉니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { ListJobsCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = {
  MaxResults: 10,
  Order: "ASCENDING",
  Queue: "QUEUE_ARN",
  Status: "SUBMITTED", // e.g., "SUBMITTED"
};

const run = async () => {
  try {
    const data = await emcClient.send(new ListJobsCommand(params));
    console.log("Success. Jobs: ", data.Jobs);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_listjobs.js 
```

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

# MediaConvert에서 작업 템플릿 사용
<a name="emc-examples-templates"></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 코드 예제는 다음을 보여 줍니다.**
+ AWS Elemental MediaConvert 작업 템플릿을 생성하는 방법.
+ 작업 템플릿을 사용하여 트랜스코딩 작업을 생성하는 방법.
+ 모든 작업 템플릿의 목록을 표시하는 방법.
+ 작업 템플릿을 삭제하는 방법.

## 시나리오
<a name="emc-examples-templates-scenario"></a>

MediaConvert에서 트랜스코딩 작업을 생성하는 데 필요한 JSON은 많은 수의 설정을 포함하여 세부적입니다. 후속 작업을 생성하는 데 사용할 수 있는 작업 템플릿에 알려진 좋은 설정을 저장하여 작업 생성을 대폭 간소화할 수 있습니다. 이 예에서는 Node.js 모듈을 사용해 MediaConvert를 직접적으로 호출하여 작업 템플릿을 생성, 사용 및 관리합니다. 이 코드는 SDK for JavaScript에서 MediaConvert 클라이언트 클래스의 다음 메서드를 사용하여 이 작업을 수행합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/CreateJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/DeleteJobTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/DeleteJobTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobTemplatesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-mediaconvert/Class/ListJobTemplatesCommand/)

## 사전 필수 작업
<a name="emc-example-templates-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 다음 작업을 완료합니다.
+ 이러한 노드 TypeScript 예를 실행하도록 프로젝트 환경을 설정하고 필수 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/mediaconvert/README.md)의 지침을 따릅니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.
+ 출력 파일이 저장된 Amazon S3 버킷 및 입력 파일에 대한 액세스 권한을 MediaConvert에 부여하는 IAM 역할을 생성합니다. 자세한 내용은 *AWS Elemental MediaConvert 사용 설명서*의 [Set up IAM permissions](https://docs.aws.amazon.com/mediaconvert/latest/ug/iam-role.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="emc-examples-templates-create"></a>

파일 이름이 `emc_create_jobtemplate.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다.

템플릿 생성을 위한 파라미터 JSON을 지정합니다. 이전에 성공한 작업에서 대부분의 JSON 파라미터를 사용하여 템플릿에서 `Settings` 값을 지정할 수 있습니다. 이 예제에서는 [MediaConvert에서 트랜스코딩 작업 생성 및 관리](emc-examples-jobs.md)의 작업 설정을 사용합니다.

파라미터를 전달하는 `MediaConvert` 클라이언트 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하여 `CreateJobTemplateCommand` 메서드를 직접적으로 호출합니다.

**참고**  
*JOB\$1QUEUE\$1ARN*을 확인할 작업 대기열의 Amazon 리소스 이름(ARN)으로 바꾸고, *BUCKET\$1NAME*을 대상 Amazon S3 버킷의 이름(예: "s3://BUCKET\$1NAME/")으로 바꿉니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { CreateJobTemplateCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

const params = {
  Category: "YouTube Jobs",
  Description: "Final production transcode",
  Name: "DemoTemplate",
  Queue: "JOB_QUEUE_ARN", //JOB_QUEUE_ARN
  Settings: {
    OutputGroups: [
      {
        Name: "File Group",
        OutputGroupSettings: {
          Type: "FILE_GROUP_SETTINGS",
          FileGroupSettings: {
            Destination: "BUCKET_NAME", // BUCKET_NAME e.g., "s3://BUCKET_NAME/"
          },
        },
        Outputs: [
          {
            VideoDescription: {
              ScalingBehavior: "DEFAULT",
              TimecodeInsertion: "DISABLED",
              AntiAlias: "ENABLED",
              Sharpness: 50,
              CodecSettings: {
                Codec: "H_264",
                H264Settings: {
                  InterlaceMode: "PROGRESSIVE",
                  NumberReferenceFrames: 3,
                  Syntax: "DEFAULT",
                  Softness: 0,
                  GopClosedCadence: 1,
                  GopSize: 90,
                  Slices: 1,
                  GopBReference: "DISABLED",
                  SlowPal: "DISABLED",
                  SpatialAdaptiveQuantization: "ENABLED",
                  TemporalAdaptiveQuantization: "ENABLED",
                  FlickerAdaptiveQuantization: "DISABLED",
                  EntropyEncoding: "CABAC",
                  Bitrate: 5000000,
                  FramerateControl: "SPECIFIED",
                  RateControlMode: "CBR",
                  CodecProfile: "MAIN",
                  Telecine: "NONE",
                  MinIInterval: 0,
                  AdaptiveQuantization: "HIGH",
                  CodecLevel: "AUTO",
                  FieldEncoding: "PAFF",
                  SceneChangeDetect: "ENABLED",
                  QualityTuningLevel: "SINGLE_PASS",
                  FramerateConversionAlgorithm: "DUPLICATE_DROP",
                  UnregisteredSeiTimecode: "DISABLED",
                  GopSizeUnits: "FRAMES",
                  ParControl: "SPECIFIED",
                  NumberBFramesBetweenReferenceFrames: 2,
                  RepeatPps: "DISABLED",
                  FramerateNumerator: 30,
                  FramerateDenominator: 1,
                  ParNumerator: 1,
                  ParDenominator: 1,
                },
              },
              AfdSignaling: "NONE",
              DropFrameTimecode: "ENABLED",
              RespondToAfd: "NONE",
              ColorMetadata: "INSERT",
            },
            AudioDescriptions: [
              {
                AudioTypeControl: "FOLLOW_INPUT",
                CodecSettings: {
                  Codec: "AAC",
                  AacSettings: {
                    AudioDescriptionBroadcasterMix: "NORMAL",
                    RateControlMode: "CBR",
                    CodecProfile: "LC",
                    CodingMode: "CODING_MODE_2_0",
                    RawFormat: "NONE",
                    SampleRate: 48000,
                    Specification: "MPEG4",
                    Bitrate: 64000,
                  },
                },
                LanguageCodeControl: "FOLLOW_INPUT",
                AudioSourceName: "Audio Selector 1",
              },
            ],
            ContainerSettings: {
              Container: "MP4",
              Mp4Settings: {
                CslgAtom: "INCLUDE",
                FreeSpaceBox: "EXCLUDE",
                MoovPlacement: "PROGRESSIVE_DOWNLOAD",
              },
            },
            NameModifier: "_1",
          },
        ],
      },
    ],
    AdAvailOffset: 0,
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
      },
    ],
    TimecodeConfig: {
      Source: "EMBEDDED",
    },
  },
};

const run = async () => {
  try {
    // Create a promise on a MediaConvert object
    const data = await emcClient.send(new CreateJobTemplateCommand(params));
    console.log("Success!", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_create_jobtemplate.js 
```

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

## 작업 템플릿에서 트랜스코딩 작업 생성
<a name="emc-examples-templates-createjob"></a>

파일 이름이 `emc_template_createjob.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다.

사용할 작업 템플릿의 이름, 생성하는 작업에 특정하게 사용할 `Settings`를 포함하여 작업 생성 파라미터 JSON을 생성합니다. 그런 다음, 파라미터를 전달하는 `MediaConvert` 클라이언트 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하여 `CreateJobsCommand` 메서드를 직접적으로 호출합니다.

**참고**  
*JOB\$1QUEUE\$1ARN*을 확인할 작업 대기열의 Amazon 리소스 이름(ARN)으로 바꾸고, *KEY\$1PAIR\$1NAME*, *TEMPLATE\$1NAME*, *ROLE\$1ARN*을 역할의 Amazon 리소스 이름(ARN)으로 바꾸고, *INPUT\$1BUCKET\$1AND\$1FILENAME*을 입력 버킷 및 파일 이름(예: "s3://BUCKET\$1NAME/FILE\$1NAME")으로 바꿉니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { CreateJobCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

const params = {
  Queue: "QUEUE_ARN", //QUEUE_ARN
  JobTemplate: "TEMPLATE_NAME", //TEMPLATE_NAME
  Role: "ROLE_ARN", //ROLE_ARN
  Settings: {
    Inputs: [
      {
        AudioSelectors: {
          "Audio Selector 1": {
            Offset: 0,
            DefaultSelection: "NOT_DEFAULT",
            ProgramSelection: 1,
            SelectorType: "TRACK",
            Tracks: [1],
          },
        },
        VideoSelector: {
          ColorSpace: "FOLLOW",
        },
        FilterEnable: "AUTO",
        PsiControl: "USE_PSI",
        FilterStrength: 0,
        DeblockFilter: "DISABLED",
        DenoiseFilter: "DISABLED",
        TimecodeSource: "EMBEDDED",
        FileInput: "INPUT_BUCKET_AND_FILENAME", //INPUT_BUCKET_AND_FILENAME, e.g., "s3://BUCKET_NAME/FILE_NAME"
      },
    ],
  },
};

const run = async () => {
  try {
    const data = await emcClient.send(new CreateJobCommand(params));
    console.log("Success! ", data);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_template_createjob.js 
```

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

## 작업 템플릿 목록 표시
<a name="emc-examples-templates-listing"></a>

파일 이름이 `emc_listtemplates.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다.

`listTemplates` 클라이언트 클래스의 `MediaConvert` 메서드에 대한 요청 파라미터를 전달할 객체를 생성합니다. 나열할 템플릿(`NAME`, `CREATION DATE`, `SYSTEM`), 나열할 개수 및 정렬 순서를 결정하는 값을 포함시킵니다. `ListTemplatesCommand` 메서드를 직접적으로 호출하려면 MediaConvert 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하고 파라미터를 전달합니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { ListJobTemplatesCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

const params = {
  ListBy: "NAME",
  MaxResults: 10,
  Order: "ASCENDING",
};

const run = async () => {
  try {
    const data = await emcClient.send(new ListJobTemplatesCommand(params));
    console.log("Success ", data.JobTemplates);
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_listtemplates.js 
```

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

## 작업 템플릿 삭제
<a name="emc-examples-templates-delete"></a>

파일 이름이 `emc_deletetemplate.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다.

삭제하려는 작업 템플릿의 이름을 `DeleteJobTemplateCommand` 클라이언트 클래스의 `MediaConvert` 메서드에 대한 파라미터로 전달할 객체를 생성합니다. `DeleteJobTemplateCommand` 메서드를 직접적으로 호출하려면 MediaConvert 서비스 객체를 간접적으로 호출하기 위한 promise를 생성하고 파라미터를 전달합니다.

```
// Import required AWS-SDK clients and commands for Node.js
import { DeleteJobTemplateCommand } from "@aws-sdk/client-mediaconvert";
import { emcClient } from "./libs/emcClient.js";

// Set the parameters
const params = { Name: "test" }; //TEMPLATE_NAME

const run = async () => {
  try {
    const data = await emcClient.send(new DeleteJobTemplateCommand(params));
    console.log(
      "Success, template deleted! Request ID:",
      data.$metadata.requestId,
    );
    return data;
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node emc_deletetemplate.js 
```

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

# AWS Lambda 예제
<a name="lambda-examples"></a>

AWS Lambda는 서버 프로비저닝 또는 관리, 워크로드 인식 클러스터 규모 조정 로직 생성, 이벤트 통합 유지 또는 런타임 관리 없이도 코드를 실행할 수 있게 지원하는 서버리스 컴퓨팅 서비스입니다.

AWS Lambda용 JavaScript API는 [LambdaService](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-lambda/) 클라이언트 클래스를 통해 노출됩니다.

다음은 AWS SDK for JavaScript v3에서 Lambda 함수를 생성하고 사용하는 방법을 보여주는 예 목록입니다.
+ [API Gateway를 사용하여 Lambda 호출](api-gateway-invoking-lambda-example.md)
+ [AWS Lambda 함수를 실행하기 위한 예약된 이벤트 생성](scheduled-events-invoking-lambda-example.md)

# Amazon Lex 예
<a name="lex-examples"></a>

Amazon Lex는 음성 및 텍스트를 사용하는 애플리케이션에 대화형 인터페이스를 구축하기 위한 AWS 서비스입니다.

Amazon Lex용 JavaScript API는 [Lex Runtime Service](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-lex-runtime-service/) 클라이언트 클래스를 통해 노출됩니다.
+ [Amazon Lex 챗봇 빌드](lex-bot-example.md)

# Amazon Polly 예
<a name="polly-examples"></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 S3에 Amazon Polly를 사용해 녹음한 오디오 업로드

## 시나리오
<a name="polly-example-synthesize-to-s3-scenario"></a>

이 예에서는 일련의 Node.js 모듈에서 Amazon S3 클라이언트 클래스의 다음 메서드를 사용하여 Amazon Polly를 사용해 녹음한 오디오를 Amazon S3에 자동으로 업로드합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-polly/Class/StartSpeechSynthesisTaskCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-polly/Class/StartSpeechSynthesisTaskCommand/)

## 사전 필수 작업
<a name="polly-example-synthesize-to-s3-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/master/javascriptv3/example_code/s3/README.md)의 지침에 따라 노드 JavaScript 예를 실행하도록 프로젝트 환경을 설정합니다.
+ 사용자 자격 증명을 사용하여 공유 구성 파일을 생성합니다. 공유 보안 인증 파일 제공에 관한 자세한 내용은 *AWS SDK 및 도구 참조 가이드*의 [Shared config and credentials files](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html) 단원을 참조하세요.
+  AWS Identity and Access Management (IAM) 인증되지 않은 Amazon Cognito 사용자 역할 polly:SynthesizeSpeech 권한과 IAM 역할이 연결된 Amazon Cognito 자격 증명 풀을 생성합니다. 아래 [를 사용하여 AWS 리소스 생성 CloudFormation](#polly-example-synthesize-to-s3-create-resources) 단원에서는 이러한 리소스를 생성하는 방법을 설명합니다.

**참고**  
이 예제에서는 Amazon Cognito를 사용하지만 Amazon Cognito를 사용하지 않는 경우 AWS 사용자에게 다음 IAM 권한 정책이 있어야 합니다.  

****  

```
{
  "Version":"2012-10-17",		 	 	 
  "Statement": [
    {
      "Action": [
        "mobileanalytics:PutEvents",
        "cognito-sync:*"
      ],
      "Resource": "*",
      "Effect": "Allow"
    },
    {
      "Action": "polly:SynthesizeSpeech",
      "Resource": "*",
      "Effect": "Allow"
    }
  ]
}
```

## 를 사용하여 AWS 리소스 생성 CloudFormation
<a name="polly-example-synthesize-to-s3-create-resources"></a>

CloudFormation 를 사용하면 AWS 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

 CloudFormation 스택을 생성하려면:

1. [AWS CLI 사용 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)의 AWS CLI 지침에 따라를 설치하고 구성합니다.

1. 프로젝트 폴더의 루트 디렉터리에 이름이 `setup.yaml`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/polly/general-examples/src/setup.yaml) 내용을 해당 파일에 복사합니다.
**참고**  
 CloudFormation 템플릿은 [ GitHub에서 사용할](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/javascript_example_code_polly_aws_service/) 수 있는를 AWS CDK 사용하여 생성되었습니다. 에 대한 자세한 내용은 [AWS Cloud Development Kit (AWS CDK) 개발자 안내서](https://docs.aws.amazon.com/cdk/latest/guide/)를 AWS CDK참조하세요.

1. 명령줄에서 다음 명령을 실행하여 *STACK\$1NAME*을 스택의 고유한 이름으로 바꿉니다.
**중요**  
스택 이름은 AWS 리전 및 AWS 계정 내에서 고유해야 합니다. 최대 128자까지 지정할 수 있으며 숫자와 하이픈을 사용할 수 있습니다.

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` 명령 파라미터에 대한 자세한 내용은 [AWS CLI 명령 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 및 [CloudFormation 사용 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)를 참조하세요.

1.  CloudFormation 관리 콘솔로 이동하여 **스택**을 선택하고 스택 이름을 선택한 다음 **리소스** 탭을 선택하여 생성된 리소스 목록을 봅니다.  
![\[CloudFormation 리소스\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/cfn_polly.png)

## Amazon S3에 Amazon Polly를 사용해 녹음한 오디오 업로드
<a name="polly-example-synthesize-to-s3-example"></a>

파일 이름이 `polly_synthesize_to_s3.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 코드에 *REGION* 및 *BUCKET\$1NAME*을 입력합니다. Amazon Polly에 액세스하려면 `Polly` 클라이언트 서비스 객체를 생성합니다. *"IDENTITY\$1POOL\$1ID"*를 이 예에서 생성한 Amazon Cognito 자격 증명 풀의 **샘플 페이지**에 있는 `IdentityPoolId`로 바꿉니다. 이는 각 클라이언트 객체에도 전달됩니다.

Amazon Polly 클라이언트 서비스 객체의 `StartSpeechSynthesisCommand` 메서드를 직접적으로 호출하여 음성 메시지를 합성해서 Amazon S3 버킷에 업로드합니다.

```
import { StartSpeechSynthesisTaskCommand } from "@aws-sdk/client-polly";
import { pollyClient } from "./libs/pollyClient.js";

// Create the parameters
const params = {
  OutputFormat: "mp3",
  OutputS3BucketName: "videoanalyzerbucket",
  Text: "Hello David, How are you?",
  TextType: "text",
  VoiceId: "Joanna",
  SampleRate: "22050",
};

const run = async () => {
  try {
    await pollyClient.send(new StartSpeechSynthesisTaskCommand(params));
    console.log(`Success, audio file added to ${params.OutputS3BucketName}`);
  } catch (err) {
    console.log("Error putting object", err);
  }
};
run();
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/master/javascriptv3/example_code/polly/general-examples/src/polly_synthesize_to_s3.js)에서 찾을 수 있습니다.

# Amazon Redshift 예
<a name="redshift-examples"></a>

Amazon Redshift는 클라우드에서 완전히 관리되는 페타바이트급 데이터 웨어하우스 서비스입니다. Amazon Redshift 데이터 웨어하우스는 *노드*라는 컴퓨팅 리소스의 모음으로, 노드는 *클러스터*라는 그룹을 구성합니다. 각 클러스터는 Amazon Redshift 엔진을 실행하며, 하나 이상의 데이터베이스를 포함합니다.

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


Amazon Redshift용 JavaScript API는 [Amazon Redshift](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/Redshift/) 클라이언트 클래스를 통해 노출됩니다.

**Topics**
+ [

# Amazon Redshift 예
](redshift-examples-section.md)

# Amazon Redshift 예
<a name="redshift-examples-section"></a>

이 예에서는 일련의 Node.js 모듈에서 `Redshift` 클라이언트 클래스의 다음 메서드를 사용하여 Amazon Redshift 클러스터의 파라미터를 생성, 수정, 설명하고 클러스터를 삭제합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/CreateClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/CreateClusterCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/ModifyClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/ModifyClusterCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DescribeClustersCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DescribeClustersCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DeleteClusterCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-redshift/Class/DeleteClusterCommand/)

Amazon Redshift 사용자에 관한 자세한 내용은 [Amazon Redshift 시작 안내서](https://docs.aws.amazon.com/redshift/latest/gsg/getting-started.html)를 참조하세요.

## 사전 필수 작업
<a name="s3-example-configuring-buckets-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예를 실행하도록 프로젝트 환경을 설정하고 필수 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/redshift/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) 단원을 참조하세요.

## Amazon Redshift 클러스터 생성
<a name="redshift-create-cluster"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Redshift 클러스터를 생성하는 방법을 보여줍니다. 자세한 내용은 [CreateCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_CreateCluster) 단원을 참조하세요.

**중요**  
*생성하려는 클러스터가 활성화됩니다(샌드박스에서 실행되지 않음). 클러스터를 삭제할 때까지 클러스터에 대해 기본 Amazon Redshift 사용 요금이 청구됩니다. 클러스터를 생성할 때와 같은 작업 기간 내에 해당 클러스터를 삭제하면 총 청구 비용이 가장 적게 듭니다. * 

`libs` 디렉터리를 생성하고 파일 이름이 `redshiftClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Redshift 클라이언트 객체가 생성됩니다. *REGION*을 AWS 리전으로 바꿉니다.

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

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

파일 이름이 `redshift-create-cluster.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 프로비저닝할 노드 유형, 클러스터에 자동으로 생성되는 데이터베이스 인스턴스의 마스터 로그인 보안 인증, 마지막으로 클러스터 유형을 지정하여 파라미터 객체를 생성합니다.

**참고**  
*CLUSTER\$1NAME*을 클러스터 이름으로 바꿉니다. *NODE\$1TYPE*의 경우 프로비저닝할 노드 유형(예: 'dc2.large')을 지정합니다. *MASTER\$1USERNAME* 및 *MASTER\$1USER\$1PASSWORD*는 클러스터에 있는 DB 인스턴스의 마스터 사용자 로그인 보안 인증 정보입니다. *CLUSTER\$1TYPE*에는 클러스터 유형을 입력합니다. `single-node`를 지정하는 경우 `NumberOfNodes` 파라미터가 필요하지 않습니다. 나머지 파라미터는 선택 사항입니다.

```
// Import required AWS SDK clients and commands for Node.js
import { CreateClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME", // Required
  NodeType: "NODE_TYPE", //Required
  MasterUsername: "MASTER_USER_NAME", // Required - must be lowercase
  MasterUserPassword: "MASTER_USER_PASSWORD", // Required - must contain at least one uppercase letter, and one number
  ClusterType: "CLUSTER_TYPE", // Required
  IAMRoleARN: "IAM_ROLE_ARN", // Optional - the ARN of an IAM role with permissions your cluster needs to access other AWS services on your behalf, such as Amazon S3.
  ClusterSubnetGroupName: "CLUSTER_SUBNET_GROUPNAME", //Optional - the name of a cluster subnet group to be associated with this cluster. Defaults to 'default' if not specified.
  DBName: "DATABASE_NAME", // Optional - defaults to 'dev' if not specified
  Port: "PORT_NUMBER", // Optional - defaults to '5439' if not specified
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new CreateClusterCommand(params));
    console.log(
      `Cluster ${data.Cluster.ClusterIdentifier} successfully created`,
    );
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node redshift-create-cluster.js  
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-create-cluster.js)에서 찾을 수 있습니다.

## Amazon Redshift 클러스터 수정
<a name="redshift-modify-cluster"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Redshift 클러스터의 마스터 사용자 암호를 수정하는 방법을 보여줍니다. 수정할 수 있는 다른 설정에 관한 자세한 내용은 [ModifyCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_ModifyCluster.html) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `redshiftClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Redshift 클라이언트 객체가 생성됩니다. *REGION*을 AWS 리전으로 바꿉니다.

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

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

파일 이름이 `redshift-modify-cluster.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. AWS 리전, 수정하려는 클러스터 이름, 새 마스터 사용자 암호를 지정합니다.

**참고**  
*CLUSTER\$1NAME*을 클러스터 이름으로 바꾸고 *MASTER\$1USER\$1PASSWORD*를 새 마스터 사용자 암호로 바꿉니다.

```
// Import required AWS SDK clients and commands for Node.js
import { ModifyClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

// Set the parameters
const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  MasterUserPassword: "NEW_MASTER_USER_PASSWORD",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new ModifyClusterCommand(params));
    console.log("Success was modified.", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node redshift-modify-cluster.js 
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-modify-cluster.js)에서 찾을 수 있습니다.

## Amazon Redshift 클러스터의 세부 정보 보기
<a name="redshift-describe-cluster"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Redshift 클러스터의 세부 정보를 확인하는 방법을 보여줍니다. 옵션에 관한 자세한 내용은 [DescribeClusters](https://docs.aws.amazon.com/redshift/latest/APIReference/API_DescribeClusters.html) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `redshiftClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Redshift 클라이언트 객체가 생성됩니다. *REGION*을 AWS 리전으로 바꿉니다.

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

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

파일 이름이 `redshift-describe-clusters.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. AWS 리전, 수정하려는 클러스터 이름, 새 마스터 사용자 암호를 지정합니다.

**참고**  
*CLUSTER\$1NAME*을 클러스터 이름으로 바꿉니다.

```
// Import required AWS SDK clients and commands for Node.js
import { DescribeClustersCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DescribeClustersCommand(params));
    console.log("Success", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node redshift-describe-clusters.js 
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-describe-clusters.js)에서 찾을 수 있습니다.

## Amazon Redshift 클러스터 삭제
<a name="redshift-delete-cluster"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Redshift 클러스터의 세부 정보를 확인하는 방법을 보여줍니다. 수정할 수 있는 다른 설정에 관한 자세한 내용은 [DeleteCluster](https://docs.aws.amazon.com/redshift/latest/APIReference/API_DeleteCluster.html) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `redshiftClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Redshift 클라이언트 객체가 생성됩니다. *REGION*을 AWS 리전으로 바꿉니다.

```
import  { RedshiftClient }  from  "@aws-sdk/client-redshift";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Redshift service object.
const redshiftClient = new RedshiftClient({ region: REGION });
export { redshiftClient };
```

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

파일 이름이 `redshift-delete-clusters.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. AWS 리전, 수정하려는 클러스터 이름, 새 마스터 사용자 암호를 지정합니다. 삭제하기 전에 클러스터의 최종 스냅샷을 저장할지 여부를 지정하고, 저장할 경우 스냅샷의 ID를 지정합니다.

**참고**  
*CLUSTER\$1NAME*을 클러스터 이름으로 바꿉니다. *SkipFinalClusterSnapshot*의 경우 클러스터를 삭제하기 전에 해당 클러스터의 최종 스냅샷을 생성할지 여부를 지정합니다. 'false'를 지정하는 경우 *CLUSTER\$1SNAPSHOT\$1ID*에 최종 클러스터 스냅샷의 ID를 지정합니다. **클러스터** 대시보드에서 클러스터에 대한 **스냅샷** 열의 링크를 클릭하고 **스냅샷** 창까지 아래로 스크롤하여 이 ID를 얻을 수 있습니다. `rs:` 스템은 스냅샷 ID의 일부가 아닙니다.

```
// Import required AWS SDK clients and commands for Node.js
import { DeleteClusterCommand } from "@aws-sdk/client-redshift";
import { redshiftClient } from "./libs/redshiftClient.js";

const params = {
  ClusterIdentifier: "CLUSTER_NAME",
  SkipFinalClusterSnapshot: false,
  FinalClusterSnapshotIdentifier: "CLUSTER_SNAPSHOT_ID",
};

const run = async () => {
  try {
    const data = await redshiftClient.send(new DeleteClusterCommand(params));
    console.log("Success, cluster deleted. ", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node redshift-delete-cluster.js  
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/redshift/src/redshift-delete-cluster.js)에서 찾을 수 있습니다.

# Amazon Simple Email Service 예
<a name="ses-examples"></a>

Amazon Simple Email Service(Amazon SES)는 디지털 마케팅 담당자 및 애플리케이션 개발자가 마케팅, 알림 및 거래 이메일을 전송하는 데 도움이 되도록 설계된 클라우드 기반 이메일 전송 서비스입니다. 이 서비스는 이메일을 사용하여 고객과 연락하는 모든 규모의 기업을 위한 안정적이고 비용 효과적인 서비스입니다.

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


Amazon SES용 JavaScript API는 `SES` 클라이언트 클래스를 통해 노출됩니다. Amazon SES 클라이언트 클래스 사용에 관한 자세한 내용은 API 참조의 [Class: SES](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SES/)를 참조하세요.

**Topics**
+ [

# Amazon SES 자격 증명 관리
](ses-examples-managing-identities.md)
+ [

# Amazon SES에서 이메일 템플릿 작업
](ses-examples-creating-template.md)
+ [

# Amazon SES를 사용하여 이메일 전송
](ses-examples-sending-email.md)

# Amazon SES 자격 증명 관리
<a name="ses-examples-managing-identities"></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 SES에 사용되는 이메일 주소 및 도메인을 확인하는 방법
+ Amazon SES 자격 증명에 AWS Identity and Access Management (IAM) 정책을 할당하는 방법.
+  AWS 계정의 모든 Amazon SES 자격 증명을 나열하는 방법.
+ Amazon SES에 사용되는 자격 증명을 삭제하는 방법

Amazon SES *자격 증명*은 Amazon SES에서 이메일을 보내는 데 사용하는 이메일 주소 또는 도메인입니다. Amazon SES에서는 이메일 자격 증명을 확인해야 합니다. 이렇게 해당 자격 증명을 소유하고 있음을 확인하고 다른 사람이 이를 사용하지 못하게 방지합니다.

Amazon SES에서 이메일 주소 및 도메인을 확인하는 방법에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [Amazon SES에서 확인된 자격 증명](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html) 단원을 참조하세요. Amazon SES의 전송 권한 부여에 관한 자세한 내용은 [Overview of Amazon SES sending authorization](Amazon Simple Email Service Developer Guidesending-authorization-overview.html) 단원을 참조하세요.

## 시나리오
<a name="ses-examples-verifying-identities-scenario"></a>

이 예에서는 일련의 Node.js 모듈을 사용하여 Amazon SES 자격 증명을 확인하고 관리합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 주소와 도메인을 확인합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListIdentitiesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListIdentitiesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteIdentityCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyEmailIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyEmailIdentityCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyDomainIdentityCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/VerifyDomainIdentityCommand/)

## 사전 필수 작업
<a name="ses-examples-verifying-identities-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/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="ses-examples-listing-identities"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 주소와 도메인을 나열합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `ListIdentitiesCommand` 메서드에 대한 `IdentityType` 및 기타 파라미터를 전달할 객체를 생성합니다. `ListIdentitiesCommand` 메서드를 직접적으로 호출하려면 Amazon SES 서비스 객체를 간접적으로 호출하여 파라미터 객체를 전달합니다.

 반환된 `data`에는 `IdentityType` 파라미터로 지정된 도메인 자격 증명 배열이 포함되어 있습니다.

**참고**  
*IdentityType*을 자격 증명 유형("EmailAddress" 또는 "Domain"일 수 있음)으로 바꿉니다.

```
import { ListIdentitiesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListIdentitiesCommand = () =>
  new ListIdentitiesCommand({ IdentityType: "EmailAddress", MaxItems: 10 });

const run = async () => {
  const listIdentitiesCommand = createListIdentitiesCommand();

  try {
    return await sesClient.send(listIdentitiesCommand);
  } catch (err) {
    console.log("Failed to list identities.", err);
    return err;
  }
};
```

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

```
node ses_listidentities.js 
```

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

## 이메일 주소 자격 증명 확인
<a name="ses-examples-verifying-email"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 발신자를 확인합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

파일 이름이 `ses_verifyemailidentity.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 다운로드를 포함하여 앞서 나와 있는 것처럼 SDK를 구성합니다.

`SES` 클라이언트 클래스의 `VerifyEmailIdentityCommand` 메서드에 대한 `EmailAddress` 파라미터를 전달할 객체를 생성합니다. `VerifyEmailIdentityCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
*EMAIL\$1ADDRESS*를 name@example.com과 같은 이메일 주소로 바꿉니다.

```
// Import required AWS SDK clients and commands for Node.js
import { VerifyEmailIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const EMAIL_ADDRESS = "name@example.com";

const createVerifyEmailIdentityCommand = (emailAddress) => {
  return new VerifyEmailIdentityCommand({ EmailAddress: emailAddress });
};

const run = async () => {
  const verifyEmailIdentityCommand =
    createVerifyEmailIdentityCommand(EMAIL_ADDRESS);
  try {
    return await sesClient.send(verifyEmailIdentityCommand);
  } catch (err) {
    console.log("Failed to verify email identity.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 도메인이 확인을 위해 Amazon SES에 추가됩니다.

```
node ses_verifyemailidentity.js 
```

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

## 도메인 자격 증명 확인
<a name="ses-examples-verifying-domains"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 도메인을 확인합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `VerifyDomainIdentityCommand` 메서드에 대한 `Domain` 파라미터를 전달할 객체를 생성합니다. `VerifyDomainIdentityCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터 객체를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*DOMAIN\$1NAME*을 도메인 이름으로 바꿉니다.

```
import { VerifyDomainIdentityCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * You must have access to the domain's DNS settings to complete the
 * domain verification process.
 */
const DOMAIN_NAME = postfix(getUniqueName("Domain"), ".example.com");

const createVerifyDomainIdentityCommand = () => {
  return new VerifyDomainIdentityCommand({ Domain: DOMAIN_NAME });
};

const run = async () => {
  const VerifyDomainIdentityCommand = createVerifyDomainIdentityCommand();

  try {
    return await sesClient.send(VerifyDomainIdentityCommand);
  } catch (err) {
    console.log("Failed to verify domain.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 도메인이 확인을 위해 Amazon SES에 추가됩니다.

```
node ses_verifydomainidentity.js  
```

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

## 자격 증명 삭제
<a name="ses-examples-deleting-identities"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용되는 이메일 주소 또는 도메인을 삭제합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `DeleteIdentityCommand` 메서드에 대한 `Identity` 파라미터를 전달할 객체를 생성합니다. `DeleteIdentityCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하기 위한 `request`를 생성하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*IDENTITY\$1EMAIL*을 삭제할 자격 증명의 이메일로 바꿉니다.

```
import { DeleteIdentityCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const IDENTITY_EMAIL = "fake@example.com";

const createDeleteIdentityCommand = (identityName) => {
  return new DeleteIdentityCommand({
    Identity: identityName,
  });
};

const run = async () => {
  const deleteIdentityCommand = createDeleteIdentityCommand(IDENTITY_EMAIL);

  try {
    return await sesClient.send(deleteIdentityCommand);
  } catch (err) {
    console.log("Failed to delete identity.", err);
    return err;
  }
};
```

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

```
node ses_deleteidentity.js 
```

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

# Amazon SES에서 이메일 템플릿 작업
<a name="ses-examples-creating-template"></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 SES에서 이메일 템플릿을 사용하여 맞춤형 이메일 메시지를 전송할 수 있습니다. Amazon SES에서 이메일 템플릿을 생성하고 사용하는 방법에 대한 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [템플릿을 사용하여 Amazon SES API를 통해 맞춤형 이메일 전송](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-personalized-email-api.html) 단원을 참조하세요.

## 시나리오
<a name="ses-examples-creating-template-scenario"></a>

이 예제에서는 일련의 Node.js 모듈을 사용하여 이메일 템플릿을 작업합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListTemplatesCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/ListTemplatesCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/CreateTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/CreateTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/GetTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/GetTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/DeleteTemplateCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/UpdateTemplateCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/UpdateTemplateCommand/)

## 사전 필수 작업
<a name="ses-examples-creating-template-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/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="ses-examples-listing-templates"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `ListTemplatesCommand` 메서드에 대한 파라미터를 전달할 객체를 생성합니다. `ListTemplatesCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

```
import { ListTemplatesCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createListTemplatesCommand = (maxItems) =>
  new ListTemplatesCommand({ MaxItems: maxItems });

const run = async () => {
  const listTemplatesCommand = createListTemplatesCommand(10);

  try {
    return await sesClient.send(listTemplatesCommand);
  } catch (err) {
    console.log("Failed to list templates.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. Amazon SES가 템플릿 목록을 반환합니다.

```
node ses_listtemplates.js  
```

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

## 이메일 템플릿 가져오기
<a name="ses-examples-get-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 가져옵니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `GetTemplateCommand` 메서드에 대한 `TemplateName` 파라미터를 전달할 객체를 생성합니다. `GetTemplateCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*TEMPLATE\$1NAME*을 반환할 템플릿의 이름으로 바꿉니다.

```
import { GetTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createGetTemplateCommand = (templateName) =>
  new GetTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const getTemplateCommand = createGetTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(getTemplateCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_gettemplate.js 
```

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

## 이메일 템플릿 생성
<a name="ses-examples-create-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`TemplateName`, `HtmlPart`, `SubjectPart` 및 `TextPart`를 포함하여 `SES` 클라이언트 클래스의 `CreateTemplateCommand` 메서드에 대한 파라미터를 전달할 객체를 생성합니다. `CreateTemplateCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*TEMPLATE\$1NAME*을 새 템플릿의 이름으로 바꾸고, *HtmlPart*를 이메일의 HTML 태그 지정 콘텐츠로 바꾸고, *SubjectPart*를 이메일 제목으로 바꿉니다.

```
import { CreateTemplateCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";

const TEMPLATE_NAME = getUniqueName("TestTemplateName");

const createCreateTemplateCommand = () => {
  return new CreateTemplateCommand({
    /**
     * The template feature in Amazon SES is based on the Handlebars template system.
     */
    Template: {
      /**
       * The name of an existing template in Amazon SES.
       */
      TemplateName: TEMPLATE_NAME,
      HtmlPart: `
        <h1>Hello, {{contact.firstName}}!</h1>
        <p>
        Did you know Amazon has a mascot named Peccy?
        </p>
      `,
      SubjectPart: "Amazon Tip",
    },
  });
};

const run = async () => {
  const createTemplateCommand = createCreateTemplateCommand();

  try {
    return await sesClient.send(createTemplateCommand);
  } catch (err) {
    console.log("Failed to create template.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 템플릿이 Amazon SES에 추가됩니다.

```
node ses_createtemplate.js  
```

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

## 이메일 템플릿 업데이트
<a name="ses-examples-update-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `UpdateTemplateCommand` 메서드에 전달된 필수 `TemplateName` 파라미터와 함께 템플릿에서 업데이트하려는 `Template` 파라미터 값을 전달할 객체를 생성합니다. `UpdateTemplateCommand` 메서드를 직접적으로 호출하려면 Amazon SES 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*TEMPLATE\$1NAME*을 템플릿 이름으로 바꾸고 *HTML\$1PART*를 HTML 태그가 지정된 이메일 콘텐츠로 바꿉니다.

```
import { UpdateTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");
const HTML_PART = "<h1>Hello, World!</h1>";

const createUpdateTemplateCommand = () => {
  return new UpdateTemplateCommand({
    Template: {
      TemplateName: TEMPLATE_NAME,
      HtmlPart: HTML_PART,
      SubjectPart: "Example",
      TextPart: "Updated template text.",
    },
  });
};

const run = async () => {
  const updateTemplateCommand = createUpdateTemplateCommand();

  try {
    return await sesClient.send(updateTemplateCommand);
  } catch (err) {
    console.log("Failed to update template.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_updatetemplate.js 
```

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

## 이메일 템플릿 삭제
<a name="ses-examples-delete-template"></a>

이 예에서는 Node.js 모듈을 사용하여 Amazon SES에 사용할 이메일 템플릿을 생성합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

`SES` 클라이언트 클래스의 `DeleteTemplateCommand` 메서드에 필수 `TemplateName` 파라미터를 전달할 객체를 생성합니다. `DeleteTemplateCommand` 메서드를 직접적으로 호출하려면 Amazon SES 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*TEMPLATE\$1NAME*을 삭제할 템플릿의 이름으로 바꿉니다.

```
import { DeleteTemplateCommand } from "@aws-sdk/client-ses";
import { getUniqueName } from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

const TEMPLATE_NAME = getUniqueName("TemplateName");

const createDeleteTemplateCommand = (templateName) =>
  new DeleteTemplateCommand({ TemplateName: templateName });

const run = async () => {
  const deleteTemplateCommand = createDeleteTemplateCommand(TEMPLATE_NAME);

  try {
    return await sesClient.send(deleteTemplateCommand);
  } catch (err) {
    console.log("Failed to delete template.", err);
    return err;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. Amazon SES가 템플릿 세부 정보를 반환합니다.

```
node ses_deletetemplate.js 
```

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

# Amazon SES를 사용하여 이메일 전송
<a name="ses-examples-sending-email"></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 코드 예제는 다음을 보여 줍니다.**
+ 테스트 또는 HTML 이메일을 전송합니다.
+ 이메일 템플릿을 기반으로 이메일을 전송합니다.
+ 이메일 템플릿을 기반으로 대량 이메일을 전송합니다.

Amazon SES API에서는 이메일 메시지 작성에 대해 원하는 제어 정도에 따라 서식 지정 및 원시라는 두 가지 이메일 전송 방법을 선택할 수 있습니다. 자세한 내용은 [Amazon SES API를 사용하여 서식이 지정된 이메일 보내기](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-formatted.html) 및 [Amazon SES API를 사용하여 원시 이메일 보내기](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/send-email-raw.html) 단원을 참조하세요.

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

이 예제에서는 일련의 Node.js 모듈을 사용하여 다양한 방법으로 이메일을 전송합니다. 이 Node.js 모듈은 SDK for JavaScript에서 `SES` 클라이언트 클래스의 다음 메서드를 사용하여 이메일 템플릿을 생성하고 사용합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendTemplatedEmailCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-ses/Class/SendBulkTemplatedEmailCommand/)

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

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/ses/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="ses-examples-sending-msail-reqs"></a>

Amazon SES에서는 이메일 메시지를 작성하는 즉시 전송 대기열에 넣습니다. `SendEmailCommand` 메서드를 사용하여 이메일을 전송하려면 메시지는 다음 요구 사항을 충족해야 합니다.
+ 확인된 이메일 주소 또는 도메인에서 메시지를 전송해야 합니다. 확인되지 않은 주소 또는 도메인을 사용하여 이메일을 전송하려고 시도하면 작업 결과로 `"Email address not verified"` 오류가 발생합니다.
+ 계정이 여전히 Amazon SES 샌드박스에 있는 경우 확인된 주소 또는 도메인으로만 또는 Amazon SES 메일박스 시뮬레이터와 연결된 이메일 주소로만 전송할 수 있습니다. 자세한 내용은 Amazon Simple Email Service 개발자 안내서의 [Amazon SES에서 확인된 자격 증명](https://docs.aws.amazon.com/ses/latest/DeveloperGuide/verify-addresses-and-domains.html) 단원을 참조하세요.
+ 첨부 파일을 포함한 메시지의 총 크기는 10MB 미만이어야 합니다.
+ 메시지에 최소 하나 이상의 수신자 이메일 주소가 포함되어야 합니다. 수신자 주소는 받는 사람: 주소, 참조: 주소 또는 숨은 참조: 주소일 수 있습니다. 수신자 이메일 주소가 유효하지 않은 경우(즉, `UserName@[SubDomain.]Domain.TopLevelDomain` 형식이 아닌 경우) 메시지에 유효한 다른 수신자가 포함되어 있더라도 전체 메시지가 거부됩니다.
+ 메시지에는 받는 사람:, 참조: 및 숨은 참조: 필드 전체에서 50명을 초과하는 수신자가 포함될 수 없습니다. 더 많은 대상에게 이메일 메시지를 전송해야 하는 경우 수신자 목록을 50명 이하의 여러 그룹으로 나눈 다음 `sendEmail` 메서드를 여러 번 호출하여 각 그룹에게 메시지를 전송할 수 있습니다.

## 이메일 전송
<a name="ses-examples-sendmail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `SES` 클라이언트 클래스의 `SendEmailCommand` 메서드에 전달할 객체를 생성합니다. `SendEmailCommand` 메서드를 직접적으로 호출하려면 Amazon SES 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*toAddress*를 이메일 수신자의 주소로 바꾸고, *fromAddress*를 이메일 발신자의 이메일 주소로 바꿉니다.

```
import { SendEmailCommand } from "@aws-sdk/client-ses";
import { sesClient } from "./libs/sesClient.js";

const createSendEmailCommand = (toAddress, fromAddress) => {
  return new SendEmailCommand({
    Destination: {
      /* required */
      CcAddresses: [
        /* more items */
      ],
      ToAddresses: [
        toAddress,
        /* more To-email addresses */
      ],
    },
    Message: {
      /* required */
      Body: {
        /* required */
        Html: {
          Charset: "UTF-8",
          Data: "HTML_FORMAT_BODY",
        },
        Text: {
          Charset: "UTF-8",
          Data: "TEXT_FORMAT_BODY",
        },
      },
      Subject: {
        Charset: "UTF-8",
        Data: "EMAIL_SUBJECT",
      },
    },
    Source: fromAddress,
    ReplyToAddresses: [
      /* more items */
    ],
  });
};

const run = async () => {
  const sendEmailCommand = createSendEmailCommand(
    "recipient@example.com",
    "sender@example.com",
  );

  try {
    return await sesClient.send(sendEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 이메일이 Amazon SES에서 전송하기 위해 대기됩니다.

```
node ses_sendemail.js 
```

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

## 템플릿을 사용한 이메일 전송
<a name="ses-examples-sendtemplatedemail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다. 파일 이름이 `ses_sendtemplatedemail.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성합니다.

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `SES` 클라이언트 클래스의 `SendTemplatedEmailCommand` 메서드에 전달할 객체를 생성합니다. `SendTemplatedEmailCommand` 메서드를 직접적으로 호출하려면 Amazon SES 클라이언트 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*REGION*을 AWS 리전으로, *USER*를 이메일을 보낼 이름과 이메일 주소로, *VERIFIED\$1EMAIL*을 이메일을 보낼 이메일 주소로, *TEMPLATE\$1NAME*을 템플릿 이름으로 바꿉니다.

```
import { SendTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL = postfix(getUniqueName("Bilbo"), "@example.com");

const USER = { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL };

/**
 *
 * @param { { emailAddress: string, firstName: string } } user
 * @param { string } templateName - The name of an existing template in Amazon SES.
 * @returns { SendTemplatedEmailCommand }
 */
const createReminderEmailCommand = (user, templateName) => {
  return new SendTemplatedEmailCommand({
    /**
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{contact.firstName}},</h1><p>Don't forget about the party gifts!</p>
     * Destination: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destination: { ToAddresses: [user.emailAddress] },
    TemplateData: JSON.stringify({ contact: { firstName: user.firstName } }),
    Source: VERIFIED_EMAIL,
    Template: templateName,
  });
};

const run = async () => {
  const sendReminderEmailCommand = createReminderEmailCommand(
    USER,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendReminderEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 이메일이 Amazon SES에서 전송하기 위해 대기됩니다.

```
node ses_sendtemplatedemail.js 
```

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

## 템플릿을 사용한 대량 이메일 전송
<a name="ses-examples-sendbulktemplatedemail"></a>

이 예제에서는 Node.js 모듈을 사용하여 Amazon SES에서 이메일을 전송합니다.

`libs` 디렉터리를 생성하고 파일 이름이 `sesClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon SES 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { SESClient } from "@aws-sdk/client-ses";
// Set the AWS Region.
const REGION = "us-east-1";
// Credentials are automatically resolved using the AWS SDK credential provider chain.
// For more information, see https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/setting-credentials-node.html
// Create SES service object.
const sesClient = new SESClient({ region: REGION });
export { sesClient };
```

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

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

발신자 및 수신자 주소, 제목, 일반 텍스트 및 HTML 형식의 이메일 본문을 포함하여 전송할 이메일을 정의하는 파라미터 값을 `SES` 클라이언트 클래스의 `SendBulkTemplatedEmailCommand` 메서드에 전달할 객체를 생성합니다. `SendBulkTemplatedEmailCommand` 메서드를 직접적으로 호출하려면 Amazon SES 서비스 객체를 간접적으로 호출하여 파라미터를 전달합니다.

**참고**  
이 예제에서는 필요한 AWS Service V3 패키지 클라이언트, V3 명령을 가져오고 사용하며 비동기/대기 패턴에서 `send` 메서드를 사용합니다. 대신 몇 가지 사소한 변경을 통해 V2 명령을 사용하여 이 예를 생성할 수 있습니다. 자세한 내용은 [v3 명령 사용](migrating.md#using_v3_commands)을 참조하세요.

**참고**  
*USERS*를 이메일 수신자의 이름과 이메일 주소로 바꾸고, *VERIFIED\$1EMAIL\$11*을 이메일 발신자의 이메일 주소로 바꾸고, *TEMPLATE\$1NAME*을 템플릿 이름으로 바꿉니다.

```
import { SendBulkTemplatedEmailCommand } from "@aws-sdk/client-ses";
import {
  getUniqueName,
  postfix,
} from "@aws-doc-sdk-examples/lib/utils/util-string.js";
import { sesClient } from "./libs/sesClient.js";

/**
 * Replace this with the name of an existing template.
 */
const TEMPLATE_NAME = getUniqueName("ReminderTemplate");

/**
 * Replace these with existing verified emails.
 */
const VERIFIED_EMAIL_1 = postfix(getUniqueName("Bilbo"), "@example.com");
const VERIFIED_EMAIL_2 = postfix(getUniqueName("Frodo"), "@example.com");

const USERS = [
  { firstName: "Bilbo", emailAddress: VERIFIED_EMAIL_1 },
  { firstName: "Frodo", emailAddress: VERIFIED_EMAIL_2 },
];

/**
 *
 * @param { { emailAddress: string, firstName: string }[] } users
 * @param { string } templateName the name of an existing template in SES
 * @returns { SendBulkTemplatedEmailCommand }
 */
const createBulkReminderEmailCommand = (users, templateName) => {
  return new SendBulkTemplatedEmailCommand({
    /**
     * Each 'Destination' uses a corresponding set of replacement data. We can map each user
     * to a 'Destination' and provide user specific replacement data to create personalized emails.
     *
     * Here's an example of how a template would be replaced with user data:
     * Template: <h1>Hello {{name}},</h1><p>Don't forget about the party gifts!</p>
     * Destination 1: <h1>Hello Bilbo,</h1><p>Don't forget about the party gifts!</p>
     * Destination 2: <h1>Hello Frodo,</h1><p>Don't forget about the party gifts!</p>
     */
    Destinations: users.map((user) => ({
      Destination: { ToAddresses: [user.emailAddress] },
      ReplacementTemplateData: JSON.stringify({ name: user.firstName }),
    })),
    DefaultTemplateData: JSON.stringify({ name: "Shireling" }),
    Source: VERIFIED_EMAIL_1,
    Template: templateName,
  });
};

const run = async () => {
  const sendBulkTemplateEmailCommand = createBulkReminderEmailCommand(
    USERS,
    TEMPLATE_NAME,
  );
  try {
    return await sesClient.send(sendBulkTemplateEmailCommand);
  } catch (caught) {
    if (caught instanceof Error && caught.name === "MessageRejected") {
      /** @type { import('@aws-sdk/client-ses').MessageRejected} */
      const messageRejectedError = caught;
      return messageRejectedError;
    }
    throw caught;
  }
};
```

예를 실행하려면 명령 프롬프트에서 다음을 입력합니다. 이메일이 Amazon SES에서 전송하기 위해 대기됩니다.

```
node ses_sendbulktemplatedemail.js
```

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

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

# Amazon Transcribe 예
<a name="Transcribe-examples"></a>

Amazon Transcribe를 사용하면 개발자가 애플리케이션에 음성 텍스트 변환 기능을 쉽게 추가할 수 있습니다.

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


Amazon Transcribe용 JavaScript API는 [TranscribeService](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/Transcribe/) 클라이언트 클래스를 통해 노출됩니다.

**Topics**
+ [

# Amazon Transcribe 예
](transcribe-examples-section.md)
+ [

# Amazon Transcribe Medical 예
](transcribe-medical-examples-section.md)

# Amazon Transcribe 예
<a name="transcribe-examples-section"></a>

이 예에서는 일련의 Node.js 모듈에서 `TranscribeService` 클라이언트 클래스의 다음 메서드를 사용하여 트랜스크립션 작업을 생성, 나열 및 삭제합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/)

Amazon Transcribe 사용자에 관한 자세한 내용은 [Amazon Transcribe 개발자 안내서](https://docs.aws.amazon.com//transcribe/latest/dg/what-is-transcribe.html)를 참조하세요.

## 사전 필수 작업
<a name="transcribe-example-transcription-jobs"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/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) 단원을 참조하세요.

## Amazon Transcribe 작업 시작
<a name="transcribe-start-transcription"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe 트랜스크립션 작업을 시작하는 방법을 보여줍니다. 자세한 내용은 [StartTranscriptionJobCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartTranscriptionJobCommand/)를 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

파일 이름이 `transcribe-create-job.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 파라미터 객체를 생성하여 필수 파라미터를 지정합니다. `StartMedicalTranscriptionJobCommand` 명령을 사용하여 작업을 시작합니다.

**참고**  
*MEDICAL\$1JOB\$1NAME*을 트랜스크립션 작업 이름으로 바꿉니다. *OUTPUT\$1BUCKET\$1NAME*에 출력이 저장되는 Amazon S3 버킷을 지정합니다. *JOB\$1TYPE*에 작업 유형을 지정합니다. *SOURCE\$1LOCATION*에 소스 파일의 위치를 지정합니다. *SOURCE\$1FILE\$1LOCATION*에 입력 미디어 파일의 위치를 ​​지정합니다.

```
// Import the required AWS SDK clients and commands for Node.js
import { StartTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME",
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_LOCATION",
    // For example, "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
  OutputBucketName: "OUTPUT_BUCKET_NAME",
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-create-job.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_create_job.js)에서 찾을 수 있습니다.

## Amazon Transcribe 작업 나열
<a name="transcribe-list-jobs"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe 트랜스크립션 작업을 나열하는 방법을 보여줍니다. 수정할 수 있는 다른 설정에 관한 자세한 내용은 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

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

**참고**  
*KEY\$1WORD*를 반환된 작업 이름에 포함해야 하는 키워드로 바꿉니다.

```
// Import the required AWS SDK clients and commands for Node.js

import { ListTranscriptionJobsCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  JobNameContains: "KEYWORD", // Not required. Returns only transcription
  // job names containing this string
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new ListTranscriptionJobsCommand(params),
    );
    console.log("Success", data.TranscriptionJobSummaries);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-list-jobs.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_list_jobs.js)에서 찾을 수 있습니다.

## Amazon Transcribe 작업 삭제
<a name="transcribe-delete-job"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe 트랜스크립션 작업을 삭제하는 방법을 보여줍니다. 옵션에 관한 자세한 내용은 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

파일 이름이 `transcribe-delete-job.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. AWS 리전과 삭제할 작업의 이름을 지정합니다.

**참고**  
*JOB\$1NAME*을 삭제할 작업의 이름으로 바꿉니다.

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  TranscriptionJobName: "JOB_NAME", // Required. For example, 'transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-delete-job.js  
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_delete_job.js)에서 찾을 수 있습니다.

# Amazon Transcribe Medical 예
<a name="transcribe-medical-examples-section"></a>

이 예에서는 일련의 Node.js 모듈에서 `TranscribeService` 클라이언트 클래스의 다음 메서드를 사용하여 의료 트랜스크립션 작업을 생성, 나열 및 삭제합니다.
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListTranscriptionJobsCommand/)
+ [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteTranscriptionJobCommand/)

Amazon Transcribe 사용자에 관한 자세한 내용은 [Amazon Transcribe 개발자 안내서](https://docs.aws.amazon.com//transcribe/latest/dg/what-is-transcribe.html)를 참조하세요.

## 사전 필수 작업
<a name="transcribe-example-transcription-medical-jobs"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/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) 단원을 참조하세요.

## Amazon Transcribe Medical 트랜스크립션 작업 시작
<a name="transcribe-start-medical-transcription"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe Medical 트랜스크립션 작업을 시작하는 방법을 보여줍니다. 자세한 내용은 [startMedicalTranscriptionJob](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/StartMedicalTranscriptionJobCommand/) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

파일 이름이 `transcribe-create-medical-job.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 파라미터 객체를 생성하여 필수 파라미터를 지정합니다. `StartMedicalTranscriptionJobCommand` 명령을 사용하여 의료 작업을 시작합니다.

**참고**  
*MEDICAL\$1JOB\$1NAME*을 의료 트랜스크립션 작업 이름으로 바꿉니다. *OUTPUT\$1BUCKET\$1NAME*에 출력이 저장되는 Amazon S3 버킷을 지정합니다. *JOB\$1TYPE*에 작업 유형을 지정합니다. *SOURCE\$1LOCATION*에 소스 파일의 위치를 지정합니다. *SOURCE\$1FILE\$1LOCATION*에 입력 미디어 파일의 위치를 ​​지정합니다.

```
// Import the required AWS SDK clients and commands for Node.js
import { StartMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // Required
  OutputBucketName: "OUTPUT_BUCKET_NAME", // Required
  Specialty: "PRIMARYCARE", // Required. Possible values are 'PRIMARYCARE'
  Type: "JOB_TYPE", // Required. Possible values are 'CONVERSATION' and 'DICTATION'
  LanguageCode: "LANGUAGE_CODE", // For example, 'en-US'
  MediaFormat: "SOURCE_FILE_FORMAT", // For example, 'wav'
  Media: {
    MediaFileUri: "SOURCE_FILE_LOCATION",
    // The S3 object location of the input media file. The URI must be in the same region
    // as the API endpoint that you are calling.For example,
    // "https://transcribe-demo.s3-REGION.amazonaws.com/hello_world.wav"
  },
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new StartMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - put", data);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-create-medical-job.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_create_medical_job.js)에서 찾을 수 있습니다.

## Amazon Transcribe Medical 작업 나열
<a name="transcribe-list-medical-jobs"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe 트랜스크립션 작업을 나열하는 방법을 보여줍니다. 자세한 내용은 [ListTranscriptionMedicalJobsCommand](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/ListMedicalTranscriptionJobsCommand/) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import { TranscribeClient } from "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Transcribe service client object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

파일 이름이 `transcribe-list-medical-jobs.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 필수 파라미터를 사용하여 파라미터 객체를 생성하고 `ListMedicalTranscriptionJobsCommand` 명령을 사용하여 의료 작업을 나열합니다.

**참고**  
*KEYWORD*를 반환된 작업 이름에 포함해야 하는 키워드로 바꿉니다.

```
// Import the required AWS SDK clients and commands for Node.js

import { ListMedicalTranscriptionJobsCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  JobNameContains: "KEYWORD", // Returns only transcription job names containing this string
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new ListMedicalTranscriptionJobsCommand(params),
    );
    console.log("Success", data.MedicalTranscriptionJobName);
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-list-medical-jobs.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_list_medical_jobs.js)에서 찾을 수 있습니다.

## Amazon Transcribe Medical 작업 삭제
<a name="transcribe-delete-medical-job"></a>

이 예에서는 AWS SDK for JavaScript를 사용하여 Amazon Transcribe 트랜스크립션 작업을 삭제하는 방법을 보여줍니다. 옵션에 관한 자세한 내용은 [https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteMedicalTranscriptionJobCommand/](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/Package/-aws-sdk-client-transcribe/Class/DeleteMedicalTranscriptionJobCommand/) 단원을 참조하세요.

`libs` 디렉터리를 생성하고 파일 이름이 `transcribeClient.js`인 Node.js 모듈을 생성합니다. 이 모듈에 아래 코드를 복사하여 붙여 넣으면 Amazon Transcribe 클라이언트 객체가 생성됩니다. *REGION*을 해당 AWS 리전으로 바꿉니다.

```
import  { TranscribeClient }  from  "@aws-sdk/client-transcribe";
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create Transcribe service object.
const transcribeClient = new TranscribeClient({ region: REGION });
export { transcribeClient };
```

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

파일 이름이 `transcribe-delete-job.js`인 Node.js 모듈을 생성합니다. 필수 클라이언트 및 패키지 설치를 포함하여 앞서 나와 있는 것처럼 SDK를 구성해야 합니다. 필수 파라미터를 사용하여 파라미터 객체를 생성하고 `DeleteMedicalJobCommand` 명령을 사용하여 의료 작업을 삭제합니다.

**참고**  
*JOB\$1NAME*을 삭제할 작업의 이름으로 바꿉니다.

```
// Import the required AWS SDK clients and commands for Node.js
import { DeleteMedicalTranscriptionJobCommand } from "@aws-sdk/client-transcribe";
import { transcribeClient } from "./libs/transcribeClient.js";

// Set the parameters
export const params = {
  MedicalTranscriptionJobName: "MEDICAL_JOB_NAME", // For example, 'medical_transciption_demo'
};

export const run = async () => {
  try {
    const data = await transcribeClient.send(
      new DeleteMedicalTranscriptionJobCommand(params),
    );
    console.log("Success - deleted");
    return data; // For unit tests.
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

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

```
node transcribe-delete-medical-job.js
```

이 샘플 코드는 [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/transcribe/src/transcribe_delete_medical_job.js)에서 찾을 수 있습니다.

# Amazon EC2 인스턴스에서 Node.js 설정
<a name="setting-up-node-on-ec2-instance"></a>

SDK for JavaScript와 함께 Node.js를 사용하는 일반적인 시나리오는 Amazon Elastic Compute Cloud(Amazon EC2) 인스턴스에서 Node.js 웹 애플리케이션을 설정하고 실행하는 것입니다. 이 자습서에서는 Linux 인스턴스를 생성하고, SSH를 사용하여 해당 인스턴스에 연결한 다음, 해당 인스턴스에서 실행할 Node.js를 설치합니다.

## 사전 조건
<a name="setting-up-node-on-ec2-instance.prerequisites"></a>

이 자습서에서는 인터넷에서 접근 가능하고 SSH를 사용하여 연결할 수 있는 퍼블릭 DNS 이름으로 Linux 인스턴스를 이미 시작했다고 가정합니다. 자세한 내용은 *Amazon EC2 사용 설명서*의 [1단계: 인스턴스 시작](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/EC2_GetStarted.html#ec2-launch-instance)을 참조하세요.

**중요**  
새 Amazon EC2 인스턴스를 시작할 때 **Amazon Linux 2023** Amazon Machine Image(AMI)를 사용합니다.

보안 그룹이 `SSH`(포트 22), ` HTTP`(포트 80), `HTTPS`(포트 443) 연결을 허용하도록 구성되어야 합니다. 이러한 사전 조건에 관한 자세한 내용은 *Amazon EC2 사용 설명서*의 [Amazon EC2 사용 설정](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/get-set-up-for-amazon-ec2.html) 섹션을 참조하세요.

## 절차
<a name="setting-up-node-on-ec2-instance-procedure"></a>

다음 절차는 Amazon Linux 인스턴스에서 Node.js를 설치하는 데 도움이 됩니다. 이 서버를 사용하여 Node.js 웹 애플리케이션을 호스팅할 수 있습니다.

**Linux 인스턴스에서 Node.js를 설정하려면**

1. SSH를 사용하여 `ec2-user`로 Linux 인스턴스에 연결합니다.

1. 명령줄에 다음을 입력하여 노드 버전 관리자(`nvm`)를 설치합니다.
**주의**  
AWS 는 다음 코드를 제어하지 않습니다. 실행하기 전에 먼저 신뢰성과 무결성을 확인해야 합니다. 이 코드에 대한 자세한 내용은 [nvm](https://github.com/nvm-sh/nvm/blob/master/README.md) GitHub 리포지토리에서 확인할 수 있습니다.

   ```
   curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.39.7/install.sh | bash
   ```

   `nvm`을 사용하면 여러 버전의 Node.js를 설치할 수 있고 여러 버전 간을 전환할 수 있기 때문에 여기서는 `nvm`을 사용하여 Node.js를 설치합니다.

1. 명령줄에 다음을 입력하여 `nvm`을 로드합니다.

   ```
   source ~/.bashrc
   ```

1. 명령줄에 다음을 입력하여 nvm을 사용해 최신 LTS 버전의 Node.js를 설치합니다.

   ```
   nvm install --lts
   ```

   Node.js를 설치하면 노드 패키지 관리자(`npm`)도 설치되므로 필요에 따라 추가 모듈을 설치할 수 있습니다.

1. 명령줄에 다음을 입력하여 Node.js가 올바르게 설치되고 실행되는지 테스트합니다.

   ```
   node -e "console.log('Running Node.js ' + process.version)"
   ```

   이렇게 하면 실행 중인 Node.js의 버전을 보여 주는 메시지가 다음과 같이 표시됩니다.

    `Running Node.js VERSION` 

**참고**  
노드 설치는 현재 Amazon EC2 세션에만 적용됩니다. CLI 세션을 다시 시작하는 경우 nvm을 다시 사용하여 설치된 노드 버전을 활성화해야 합니다. 인스턴스가 종료되면 노드를 다시 설치해야 합니다. 이에 대한 대안은 다음 항목에 설명된 대로 유지하려는 구성이 있다면 Amazon EC2 인스턴스의 Amazon Machine Image(AMI)를 만드는 것입니다.

## Amazon Machine Image(AMI) 생성
<a name="setting-up-node-on-ec2-instance-create-image"></a>

Amazon EC2 인스턴스에 Node.js를 설치한 후에는 해당 인스턴스에서 Amazon Machine Image(AMI)를 생성할 수 있습니다. AMI를 생성하면 동일한 Node.js 설치에서 여러 Amazon EC2 인스턴스를 쉽게 프로비저닝할 수 있습니다. 기존 인스턴스에서 AMI를 생성하는 방법에 관한 자세한 내용은 *Amazon EC2 사용 설명서*의 [Amazon EBS 지원 Linux AMI 생성](https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/creating-an-ami-ebs.html)을 참조하세요.

## 관련 리소스
<a name="setting-up-node-on-ec2-instance-related-resource"></a>

이 주제에 사용되는 명령과 소프트웨어에 관한 자세한 내용은 다음 웹 페이지를 확인하세요.
+ 노드 버전 관리자(`nvm`) - [GitHub의 nvm 리포지토리](https://github.com/creationix/nvm)를 참조하세요.
+ 노드 패키지 관리자(`npm`) - [npm 웹 사이트](https://www.npmjs.com)를 참조하세요.

# API Gateway를 사용하여 Lambda 호출
<a name="api-gateway-invoking-lambda-example"></a>

대규모로 REST, HTTP 및 WebSocket API를 생성, 게시, 유지 관리, 모니터링 및 보호하기 위한 서비스인 Amazon API Gateway를 사용하여 Lambda 함수를 호출할 수 있습니다. AWS APIs API 개발자는 AWS 또는 기타 웹 서비스에 액세스하는 APIs와 AWS 클라우드에 저장된 데이터를 생성할 수 있습니다. API Gateway 개발자는 자체 클라이언트 애플리케이션에서 사용할 API를 생성할 수 있습니다. 자세한 내용은 [Amazon API Gateway란 무엇입니까?](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html) 단원을 참조하세요.

AWS Lambda 는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있는 컴퓨팅 서비스입니다. 다양한 프로그래밍 언어로 Lambda 함수를 생성할 수 있습니다. 에 대한 자세한 내용은 [란 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 무엇입니까?를 AWS Lambda참조하십시오.

이 예제에서는 Lambda JavaScript 런타임 API를 사용하여 Lambda 함수를 생성합니다. 이 예제에서는 다양한 AWS 서비스를 호출하여 특정 사용 사례를 수행합니다. 예를 들어 다음 그림과 같이 조직에서 1주년을 맞이하는 직원들에게 축하하는 모바일 문자 메시지를 보낸다고 가정해 보겠습니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


이 예를 완료하는 데 약 20분 정도 걸립니다.

이 예에서는 JavaScript 로직을 사용하여 이 사용 사례를 수행하는 솔루션을 생성하는 방법을 보여줍니다. 예를 들어 Lambda 함수를 사용하여 데이터베이스를 읽어 1주년 기념일을 맞이한 직원을 확인하는 방법, 데이터를 처리하고 문자 메시지를 보내는 방법을 모두 알아봅니다. 그런 다음 API Gateway를 사용하여 Rest 엔드포인트를 사용하여이 AWS Lambda 함수를 호출하는 방법을 알아봅니다. 예를 들어 다음 curl 명령을 사용하여 Lambda 함수를 간접적으로 호출할 수 있습니다.

```
curl -XGET "https://xxxxqjko1o3.execute-api.us-east-1.amazonaws.com/cronstage/employee" 
```

이 AWS 자습서에서는 이러한 필드가 포함된 Employee이라는 Amazon DynamoDB 테이블을 사용합니다.
+ **id** - 테이블의 프라이머리 키입니다.
+ **firstName** –직원의 이름입니다.
+ **phone** –직원의 전화번호입니다.
+ **startDate** – 직원의 시작 날짜입니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**중요**  
완료 비용:이 문서에 포함된 AWS 서비스는 AWS 프리 티어에 포함됩니다. 하지만 요금이 부과되지 않도록 하려면 이 예를 완료한 후에 모든 리소스를 종료해야 합니다.

**앱을 빌드하려면 다음을 수행합니다.**

1. [사전 조건 완료 ](#api-gateway-invoking-lambda-provision-resources)

1. [AWS 리소스 생성 ](#api-gateway-invoking-lambda-provision-resources)

1. [브라우저 스크립트 준비 ](#api-gateway-invoking-lambda-browser-script)

1. [Lambda 함수 생성 및 업로드 ](#api-gateway-invoking-lambda-browser-script)

1. [Lambda 함수 배포 ](#api-gateway-invoking-lambda-deploy-function)

1. [앱 실행](#api-gateway-invoking-lambda-run)

1. [리소스 삭제](#api-gateway-invoking-lambda-destroy)

## 사전 필수 작업
<a name="api-gateway-invoking-lambda-prerequisites"></a>

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

## AWS 리소스 생성
<a name="api-gateway-invoking-lambda-provision-resources"></a>

이 자습서를 시작하려면 다음 리소스가 필요합니다.
+ 이전 그림에 나와 있는 필드와 `Id`라는 키가 있는 `Employee`라는 Amazon DynamoDB 테이블. 이 사용 사례를 테스트하려는 유효한 휴대폰을 포함해 올바른 데이터를 입력했는지 확인하세요. 자세한 내용은 [테이블 생성](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)을 참조하세요.
+ Lambda 함수를 실행하기 위한 권한이 연결된 IAM 역할.
+ Lambda 함수를 호스팅하는 Amazon S3 버킷.

이러한 리소스를 수동으로 생성할 수 있지만이 자습서에 설명된 CloudFormation 대로를 사용하여 이러한 리소스를 프로비저닝하는 것이 좋습니다.

### 를 사용하여 AWS 리소스 생성 CloudFormation
<a name="api-gateway-invoking-lambda-resources-cli"></a>

CloudFormation 를 사용하면 AWS 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

를 사용하여 CloudFormation 스택을 생성하려면 AWS CLI:

1. [AWS CLI 사용 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)의 AWS CLI 지침에 따라를 설치하고 구성합니다.

1. 프로젝트 폴더의 루트 디렉터리에 이름이 `setup.yaml`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/setup.yaml) 내용을 해당 파일에 복사합니다.
**참고**  
 CloudFormation 템플릿은 [ GitHub에서 사용할](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/lambda_using_api_gateway) 수 있는를 AWS CDK 사용하여 생성되었습니다. 에 대한 자세한 내용은 [AWS Cloud Development Kit (AWS CDK) 개발자 안내서](https://docs.aws.amazon.com/cdk/latest/guide/)를 AWS CDK참조하세요.

1. 명령줄에서 다음 명령을 실행하여 *STACK\$1NAME*을 스택의 고유한 이름으로 바꿉니다.
**중요**  
스택 이름은 AWS 리전 및 AWS 계정 내에서 고유해야 합니다. 최대 128자까지 지정할 수 있으며 숫자와 하이픈을 사용할 수 있습니다.

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` 명령 파라미터에 대한 자세한 내용은 [AWS CLI 명령 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 및 [CloudFormation 사용 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)를 참조하세요.

1. 다음으로, [테이블 채우기](#api-gateway-invoking-lambda-resources-create-table) 절차에 따라 테이블을 채웁니다.

### 테이블 채우기
<a name="api-gateway-invoking-lambda-resources-create-table"></a>

테이블을 채우려면 먼저, 이름이 `libs`인 디렉터리를 생성하고 이 디렉터리 안에 이름이 `dynamoClient.js`인 파일을 생성한 다음, 아래 내용을 해당 파일에 붙여 넣습니다.

```
const { DynamoDBClient } = require ( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
 // Create an Amazon Lambda service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/dynamoClient.js) 제공합니다.

다음으로, 프로젝트 폴더의 루트 디렉터리에 이름이 `populate-table.js`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js) 내용을 해당 파일에 복사합니다. 항목 중 하나에 대해 `phone` 속성의 값을 E.164 형식의 유효한 휴대폰 번호로 바꾸고 `startDate`의 값을 오늘 날짜로 바꿉니다.

명령줄에서 다음 명령을 실행합니다.

```
node populate-table.js
```

```
const { BatchWriteItemCommand } = require ( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require ( "./libs/dynamoClient" );

// Set the parameters.
export const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js) 제공합니다.

## AWS Lambda 함수 생성
<a name="api-gateway-invoking-lambda-browser-script"></a>

### SDK 구성
<a name="api-gateway-invoking-lambda-configure-sdk"></a>

`libs` 디렉터리에서 이름이 `snsClient.js` 및 `lambdaClient.js`인 파일을 생성하고 아래 내용을 각각 해당 파일에 붙여 넣습니다.

```
const { SNSClient } = require("@aws-sdk/client-sns");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon SNS service client object.
const snsClient = new SNSClient({ region: REGION });
module.exports = { snsClient };
```

 *REGION*을 AWS 리전으로 바꿉니다. 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/snsClient.js) 제공합니다.

```
const { LambdaClient } = require("@aws-sdk/client-lambda");
// Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"
// Create an Amazon Lambda service client object.
const lambdaClient = new LambdaClient({ region: REGION });
module.exports = { lambdaClient };
```

*REGION*을 AWS 리전으로 바꿉니다. 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/libs/lambdaClient.js) 제공합니다.

먼저 필수 AWS SDK for JavaScript (v3) 모듈과 명령을 가져옵니다. 그런 다음, 오늘 날짜를 계산하여 파라미터에 할당합니다. 셋째, `ScanCommand`에 대한 파라미터를 생성합니다. *TABLE\$1NAME*을 이 예시의 [AWS 리소스 생성](#api-gateway-invoking-lambda-provision-resources) 섹션에서 생성한 테이블 이름으로 바꿉니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#api-gateway-invoking-lambda-full) 섹션을 참조하세요.)

```
const { ScanCommand } = require("@aws-sdk/client-dynamodb");
const { PublishCommand } = require("@aws-sdk/client-sns");
const { snsClient } = require("./libs/snsClient");
const { dynamoClient } = require("./libs/dynamoClient");

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = `${yyyy}-${mm}-${dd}`;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which are the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "Employees",
};
```

### DynamoDB 테이블 스캔
<a name="api-gateway-invoking-lambda-scan-table"></a>

먼저, Amazon SNS `PublishCommand`를 사용하여 텍스트 메시지를 게시하는 `sendText`라는 async/await 함수를 생성합니다. 그런 다음, DynamoDB 테이블을 스캔하여 오늘이 근무 기념일인 직원을 찾은 후 `sendText` 함수를 직접적으로 호출하여 해당 직원에게 문자 메시지를 보내는 `try` 블록 패턴을 추가합니다. 오류가 발생하면 `catch` 블록이 직접적으로 호출됩니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#api-gateway-invoking-lambda-full) 섹션을 참조하세요.)

```
// Helper function to send message using Amazon SNS.
exports.handler = async () => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      await snsClient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to identify employees with work anniversary today.
    const data = await dynamoClient.send(new ScanCommand(params));
    for (const element of data.Items) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message: `Hi ${element.firstName.S}; congratulations on your work anniversary!`,
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    }
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### Lambda 함수 번들링
<a name="api-gateway-invoking-lambda-full"></a>

이 주제에서는 `mylambdafunction.ts` 및이 예제에 필요한 AWS SDK for JavaScript 모듈을 라는 번들 파일로 번들링하는 방법을 설명합니다`index.js`.

1. webpack을 아직 설치하지 않았다면 이 예의 [사전 필수 작업](#api-gateway-invoking-lambda-prerequisites)에 따라 설치합니다.
**참고**  
*Webpack*에 관한 자세한 내용은 [Webpack으로 애플리케이션 번들링](webpack.md) 단원을 참조하세요.

1. 명령줄에서 다음을 실행하여 이 예시의 JavaScript를 `<index.js>`라는 파일로 번들링합니다.

   ```
   webpack mylambdafunction.ts --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**중요**  
출력 이름이 `index.js`인 것에 주목하세요. 이는 Lambda 함수가 작동하려면 `index.js` 핸들러가 있어야 하기 때문입니다.

1. 번들 출력 파일, `index.js`를 `mylambdafunction.zip`이라는 ZIP 파일로 압축합니다.

1. 이 자습서의 [AWS 리소스 생성](#api-gateway-invoking-lambda-provision-resources) 항목에서 생성한 Amazon S3 버킷에 `mylambdafunction.zip`을 업로드합니다.

## Lambda 함수 배포
<a name="api-gateway-invoking-lambda-deploy-function"></a>

프로젝트의 루트에서 `lambda-function-setup.ts` 파일을 생성하고 아래 내용을 해당 파일에 붙여 넣습니다.

*BUCKET\$1NAME*을 Lambda 함수의 ZIP 버전을 업로드한 Amazon S3 버킷 이름으로 바꿉니다. *ZIP\$1FILE\$1NAME*을 Lambda 함수의 ZIP 버전 이름으로 바꿉니다. *ROLE*을 이 자습서의 [AWS 리소스 생성](#api-gateway-invoking-lambda-provision-resources) 항목에서 생성한 IAM 역할의 Amazon 리소스 번호(ARN)로 바꿉니다. *LAMBDA\$1FUNCTION\$1NAME*을 Lambda 함수 이름으로 바꿉니다.

```
// Load the required Lambda client and commands.
const {
  CreateFunctionCommand
} = require ( "@aws-sdk/client-lambda" );
const { lambdaClient} = require ( "./libs/lambdaClient.js );

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email on each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambdaClient.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

명령줄에 다음을 입력하여 Lambda 함수를 배포합니다.

```
node lambda-function-setup.ts
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/lambda-function-setup.js) 제공합니다.

## Lambda 함수를 간접적으로 호출하도록 API Gateway 구성
<a name="api-gateway-invoking-lambda-run"></a>

**앱을 빌드하려면 다음을 수행합니다.**

1. [REST API 생성](#api-gateway-invoking-lambda-run-create)

1. [API Gateway 메서드 테스트](#api-gateway-invoking-lambda-run-test)

1. [API Gateway 메서드 배포](#api-gateway-invoking-lambda-run-deploy)

### REST API 생성
<a name="api-gateway-invoking-lambda-run-create"></a>

API Gateway 콘솔을 사용하여 Lambda 함수의 REST 엔드포인트를 생성할 수 있습니다. 완료하면 RESTful 호출을 사용하여 Lambda 함수를 간접적으로 호출할 수 있습니다.



1. [Amazon API Gateway 콘솔](https://console.aws.amazon.com/apigateway)에 로그인합니다.

1. REST API에서 **빌드**를 선택합니다.

1. **새 API**를 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/PicNewAPI.png)

1. **직원**을 API 이름으로 지정하고 설명을 입력합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picEmployeeAPI.png)

1. **API 생성**을 선택합니다.

1. **직원** 섹션에서 **리소스**를 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picResources.png)

1. 이름 필드에서 **직원**을 지정합니다.

1. **리소스 생성**을 선택합니다.

1. **작업** 드롭다운에서 **리소스 생성**을 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picCreateResources.png)

1. **/employees**를 선택하고, **작업**에서 **메서드 생성**을 선택한 다음, **/employees** 아래의 드롭다운 메뉴에서 **GET**을 선택합니다. 체크 표시 아이콘을 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGet.png)

1. **Lambda 함수**를 선택하고 Lambda 함수 이름으로 **mylambdafunction**을 입력합니다. **저장**을 선택합니다.

### API Gateway 메서드 테스트
<a name="api-gateway-invoking-lambda-run-test"></a>

자습서의 이 시점에서 **mylambdafunction** Lambda 함수를 간접적으로 호출하는 API Gateway 메서드를 테스트할 수 있습니다. 메서드를 테스트하려면 다음 그림과 같이 **테스트**를 선택합니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picTest.png)


Lambda 함수가 간접적으로 호출되면 로그 파일을 보고 성공 메시지를 확인할 수 있습니다.

### API Gateway 메서드 배포
<a name="api-gateway-invoking-lambda-run-deploy"></a>

테스트가 성공하면 [Amazon API Gateway 콘솔](https://console.aws.amazon.com/apigateway)에서 메서드를 배포할 수 있습니다.

1. **GET**을 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGetDeploy.png)

1. **작업** 드롭다운에서 **API 배포**를 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1. **API 배포** 양식을 작성하고 **배포**를 선택합니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1.  **변경 사항 저장(Save Changes)**을 선택합니다.

1.  **GET**을 다시 선택하면 URL이 변경된 것을 확인할 수 있습니다. 이는 Lambda 함수를 간접적으로 호출하는 데 사용할 수 있는 호출 URL입니다.  
![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picURL2.png)

## 리소스 삭제
<a name="api-gateway-invoking-lambda-destroy"></a>

축하합니다\$1 AWS SDK for JavaScript를 사용하여 Amazon API Gateway를 통해 Lambda 함수를 간접적으로 호출했습니다. 이 자습서의 시작 부분에서 설명한 것처럼 요금이 부과되지 않도록 하려면 이 자습서를 진행하는 동안 생성한 모든 리소스를 종료해야 합니다. 다음과 같이이 자습서의 [AWS 리소스 생성](#api-gateway-invoking-lambda-provision-resources) 주제에서 생성한 CloudFormation 스택을 삭제하여이 작업을 수행할 수 있습니다.

1. [CloudFormationAWS 관리 콘솔에서를]( https://console.aws.amazon.com/cloudformation/home) 엽니다.

1. **스택** 페이지를 열고 스택을 선택합니다.

1. **삭제**를 선택합니다.

# AWS Lambda 함수를 실행하기 위한 예약된 이벤트 생성
<a name="scheduled-events-invoking-lambda-example"></a>

Amazon CloudWatch 이벤트를 사용하여 AWS Lambda 함수를 호출하는 예약된 이벤트를 생성할 수 있습니다. cron 표현식을 사용하여 Lambda 함수가 간접적으로 호출되는 시기를 예약하도록 CloudWatch 이벤트를 구성할 수 있습니다. 예를 들어 평일마다 Lambda 함수를 간접적으로 호출하도록 CloudWatch 이벤트를 예약할 수 있습니다.

AWS Lambda 는 서버를 프로비저닝하거나 관리하지 않고도 코드를 실행할 수 있는 컴퓨팅 서비스입니다. 다양한 프로그래밍 언어로 Lambda 함수를 생성할 수 있습니다. 에 대한 자세한 내용은 [란 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 무엇입니까?를 AWS Lambda참조하십시오.

이 자습서에서는 Lambda JavaScript 런타임 API를 사용하여 Lambda 함수를 생성합니다. 이 예제에서는 다양한 AWS 서비스를 호출하여 특정 사용 사례를 수행합니다. 예를 들어 다음 그림과 같이 조직에서 1주년을 맞이하는 직원들에게 축하하는 모바일 문자 메시지를 보낸다고 가정해 보겠습니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picPhone.png)


이 자습서를 완료하는 데 약 20분 정도 걸립니다.

이 자습서에서는 JavaScript 로직을 사용하여 이 사용 사례를 수행하는 솔루션을 생성하는 방법을 보여줍니다. 예를 들어 Lambda 함수를 사용하여 데이터베이스를 읽어 1주년 기념일을 맞이한 직원을 확인하는 방법, 데이터를 처리하고 문자 메시지를 보내는 방법을 모두 알아봅니다. 그런 다음, cron 표현식을 사용하여 평일마다 Lambda 함수를 간접적으로 호출하는 방법을 알아봅니다.

이 AWS 자습서에서는 이러한 필드가 포함된 Employee이라는 Amazon DynamoDB 테이블을 사용합니다.
+ **id** - 테이블의 프라이머리 키입니다.
+ **firstName** –직원의 이름입니다.
+ **phone** –직원의 전화번호입니다.
+ **startDate** – 직원의 시작 날짜입니다.

![\[DynamoDB 테이블\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/apigateway_example/pic00.png)


**중요**  
완료 비용:이 문서에 포함된 AWS 서비스는 AWS 프리 티어에 포함됩니다. 하지만 요금이 부과되지 않도록 하려면 이 자습서를 완료한 후에 모든 리소스를 종료해야 합니다.

**앱을 빌드하려면 다음을 수행합니다.**

1. [사전 조건 완료 ](#scheduled-events-invoking-lambda-provision-resources)

1. [AWS 리소스 생성 ](#scheduled-events-invoking-lambda-provision-resources)

1. [브라우저 스크립트 준비 ](#scheduled-events-invoking-lambda-browser-script)

1. [Lambda 함수 생성 및 업로드 ](#scheduled-events-invoking-lambda-browser-script)

1. [Lambda 함수 배포 ](#scheduled-events-invoking-lambda-deploy-function)

1. [앱 실행](#scheduled-events-invoking-lambda-run)

1. [리소스 삭제](#scheduled-events-invoking-lambda-destroy)

## 사전 필수 작업
<a name="scheduled-events-invoking-lambda-prerequisites"></a>

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

## AWS 리소스 생성
<a name="scheduled-events-invoking-lambda-provision-resources"></a>

이 자습서를 시작하려면 다음 리소스가 필요합니다.
+ 이전 그림에 나와 있는 필드와 **Id**라는 키가 있는 **Employee**라는 Amazon DynamoDB 테이블. 이 사용 사례를 테스트하려는 유효한 휴대폰을 포함해 올바른 데이터를 입력했는지 확인하세요. 자세한 내용은 [테이블 생성](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)을 참조하세요.
+ Lambda 함수를 실행하기 위한 권한이 연결된 IAM 역할.
+ Lambda 함수를 호스팅하는 Amazon S3 버킷.

이러한 리소스를 수동으로 생성할 수 있지만이 자습서에 설명된 CloudFormation 대로를 사용하여 이러한 리소스를 프로비저닝하는 것이 좋습니다.

### 를 사용하여 AWS 리소스 생성 CloudFormation
<a name="scheduled-events-invoking-lambda-resources-cli"></a>

CloudFormation 를 사용하면 AWS 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

를 사용하여 CloudFormation 스택을 생성하려면 AWS CLI:

1. [AWS CLI 사용 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)의 AWS CLI 지침에 따라를 설치하고 구성합니다.

1. 프로젝트 폴더의 루트 디렉터리에 이름이 `setup.yaml`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/setup.yaml) 내용을 해당 파일에 복사합니다.
**참고**  
 CloudFormation 템플릿은 [ GitHub에서 사용할](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/resources/cdk/lambda_using_scheduled_events) 수 있는를 AWS CDK 사용하여 생성되었습니다. 에 대한 자세한 내용은 [AWS Cloud Development Kit (AWS CDK) 개발자 안내서](https://docs.aws.amazon.com/cdk/latest/guide/)를 AWS CDK참조하세요.

1. 명령줄에서 다음 명령을 실행하여 *STACK\$1NAME*을 스택의 고유한 이름으로 바꿉니다.
**중요**  
스택 이름은 AWS 리전 및 AWS 계정 내에서 고유해야 합니다. 최대 128자까지 지정할 수 있으며 숫자와 하이픈을 사용할 수 있습니다.

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` 명령 파라미터에 대한 자세한 내용은 [AWS CLI 명령 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 및 [CloudFormation 사용 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)를 참조하세요.

    CloudFormation 대시보드에서 스택을 열고 리소스 탭을 선택하여 콘솔의 **리소스** 목록을 봅니다. 자습서에는 이러한 정보가 필요합니다.

1. 스택이 생성되면에 설명된 대로 AWS SDK for JavaScript 를 사용하여 DynamoDB 테이블을 채웁니다[DynamoDB 테이블 채우기](#scheduled-events-invoking-lambda-resources-create-table).

### DynamoDB 테이블 채우기
<a name="scheduled-events-invoking-lambda-resources-create-table"></a>

테이블을 채우려면 먼저, 이름이 `libs`인 디렉터리를 생성하고 이 디렉터리 안에 이름이 `dynamoClient.js`인 파일을 생성한 다음, 아래 내용을 해당 파일에 붙여 넣습니다.

```
const { DynamoDBClient } = require( "@aws-sdk/client-dynamodb" );
// Set the AWS Region.
const REGION = "REGION"; // e.g. "us-east-1"
// Create an Amazon DynamoDB service client object.
const dynamoClient = new DynamoDBClient({region:REGION});
module.exports = { dynamoClient };
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/libs/dynamoClient.js) 제공합니다.

다음으로, 프로젝트 폴더의 루트 디렉터리에 이름이 `populate-table.js`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-api-gateway/src/helper-functions/populate-table.js) 내용을 해당 파일에 복사합니다. 항목 중 하나에 대해 `phone` 속성의 값을 E.164 형식의 유효한 휴대폰 번호로 바꾸고 `startDate`의 값을 오늘 날짜로 바꿉니다.

명령줄에서 다음 명령을 실행합니다.

```
node populate-table.js
```

```
const {
BatchWriteItemCommand } = require( "aws-sdk/client-dynamodb" );
const {dynamoClient} = require(  "./libs/dynamoClient" );
// Set the parameters.
const params = {
  RequestItems: {
    Employees: [
      {
        PutRequest: {
          Item: {
            id: { N: "1" },
            firstName: { S: "Bob" },
            phone: { N: "155555555555654" },
            startDate: { S: "2019-12-20" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "2" },
            firstName: { S: "Xing" },
            phone: { N: "155555555555653" },
            startDate: { S: "2019-12-17" },
          },
        },
      },
      {
        PutRequest: {
          Item: {
            id: { N: "55" },
            firstName: { S: "Harriette" },
            phone: { N: "155555555555652" },
            startDate: { S: "2019-12-19" },
          },
        },
      },
    ],
  },
};

export const run = async () => {
  try {
    const data = await dbclient.send(new BatchWriteItemCommand(params));
    console.log("Success", data);
  } catch (err) {
    console.log("Error", err);
  }
};
run();
```

 이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/populate-table.js) 제공합니다.

## AWS Lambda 함수 생성
<a name="scheduled-events-invoking-lambda-browser-script"></a>

### SDK 구성
<a name="scheduled-events-invoking-lambda-configure-sdk"></a>

먼저 필수 AWS SDK for JavaScript (v3) 모듈 및 명령과 `DynamoDBClient` DynamoDB `ScanCommand` `SNSClient` 및 Amazon SNS `PublishCommand` 명령을 가져옵니다. *REGION*을 AWS 리전으로 바꿉니다. 그런 다음, 오늘 날짜를 계산하여 파라미터에 할당합니다. 다음으로, `ScanCommand`.Replace *TABLE\$1NAME*의 파라미터를 이 예의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 섹션에서 생성한 테이블 이름을 사용해 생성합니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#scheduled-events-invoking-lambda-full) 섹션을 참조하세요.)

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};
```

### DynamoDB 테이블 스캔
<a name="scheduled-events-invoking-lambda-scan-table"></a>

먼저, Amazon SNS `PublishCommand`를 사용하여 텍스트 메시지를 게시하는 `sendText`라는 async/await 함수를 생성합니다. 그런 다음, DynamoDB 테이블을 스캔하여 오늘이 근무 기념일인 직원을 찾은 후 `sendText` 함수를 직접적으로 호출하여 해당 직원에게 문자 메시지를 보내는 `try` 블록 패턴을 추가합니다. 오류가 발생하면 `catch` 블록이 직접적으로 호출됩니다.

다음 코드 조각은 이 단계를 보여줍니다. (전체 예제는 [Lambda 함수 번들링](#scheduled-events-invoking-lambda-full) 섹션을 참조하세요.)

```
exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

### Lambda 함수 번들링
<a name="scheduled-events-invoking-lambda-full"></a>

이 주제에서는 `mylambdafunction.js` 및이 예제에 필요한 AWS SDK for JavaScript 모듈을 라는 번들 파일로 번들링하는 방법을 설명합니다`index.js`.

1. webpack을 아직 설치하지 않았다면 이 예의 [사전 필수 작업](#scheduled-events-invoking-lambda-prerequisites)에 따라 설치합니다.
**참고**  
*Webpack*에 관한 자세한 내용은 [Webpack으로 애플리케이션 번들링](webpack.md) 단원을 참조하세요.

1. 명령줄에서 다음을 실행하여 이 예의 JavaScript를 `<index.js>`라는 파일로 번들링합니다.

   ```
   webpack mylamdbafunction.js --mode development --target node --devtool false --output-library-target umd -o index.js
   ```
**중요**  
출력 이름이 `index.js`인 것에 주목하세요. 이는 Lambda 함수가 작동하려면 `index.js` 핸들러가 있어야 하기 때문입니다.

1. 번들 출력 파일, `index.js`를 `my-lambda-function.zip`이라는 ZIP 파일로 압축합니다.

1. 이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 항목에서 생성한 Amazon S3 버킷에 `mylambdafunction.zip`을 업로드합니다.

`mylambdafunction.js`에 대한 전체 브라우저 스크립트 코드는 다음과 같습니다.

```
"use strict";
// Load the required clients and commands.
const { DynamoDBClient, ScanCommand } = require("@aws-sdk/client-dynamodb");
const { SNSClient, PublishCommand } = require("@aws-sdk/client-sns");

//Set the AWS Region.
const REGION = "REGION"; //e.g. "us-east-1"

// Get today's date.
const today = new Date();
const dd = String(today.getDate()).padStart(2, "0");
const mm = String(today.getMonth() + 1).padStart(2, "0"); //January is 0!
const yyyy = today.getFullYear();
const date = yyyy + "-" + mm + "-" + dd;

// Set the parameters for the ScanCommand method.
const params = {
  // Specify which items in the results are returned.
  FilterExpression: "startDate = :topic",
  // Define the expression attribute value, which are substitutes for the values you want to compare.
  ExpressionAttributeValues: {
    ":topic": { S: date },
  },
  // Set the projection expression, which the the attributes that you want.
  ProjectionExpression: "firstName, phone",
  TableName: "TABLE_NAME",
};

// Create the client service objects.
const dbclient = new DynamoDBClient({ region: REGION });
const snsclient = new SNSClient({ region: REGION });

exports.handler = async (event, context, callback) => {
  // Helper function to send message using Amazon SNS.
  async function sendText(textParams) {
    try {
      const data = await snsclient.send(new PublishCommand(textParams));
      console.log("Message sent");
    } catch (err) {
      console.log("Error, message not sent ", err);
    }
  }
  try {
    // Scan the table to check identify employees with work anniversary today.
    const data = await dbclient.send(new ScanCommand(params));
    data.Items.forEach(function (element, index, array) {
      const textParams = {
        PhoneNumber: element.phone.N,
        Message:
          "Hi " +
          element.firstName.S +
          "; congratulations on your work anniversary!",
      };
      // Send message using Amazon SNS.
      sendText(textParams);
    });
  } catch (err) {
    console.log("Error, could not scan table ", err);
  }
};
```

## Lambda 함수 배포
<a name="scheduled-events-invoking-lambda-deploy-function"></a>

프로젝트의 루트에서 `lambda-function-setup.js` 파일을 생성하고 아래 내용을 해당 파일에 붙여 넣습니다.

*BUCKET\$1NAME*을 Lambda 함수의 ZIP 버전을 업로드한 Amazon S3 버킷 이름으로 바꿉니다. *ZIP\$1FILE\$1NAME*을 Lambda 함수의 ZIP 버전 이름으로 바꿉니다. *IAM\$1ROLE\$1ARN*을 이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 항목에서 생성한 IAM 역할의 Amazon 리소스 번호(ARN)로 바꿉니다. *LAMBDA\$1FUNCTION\$1NAME*을 Lambda 함수 이름으로 바꿉니다.

```
// Load the required Lambda client and commands.
const {
   CreateFunctionCommand,
} = require("@aws-sdk/client-lambda");
const {
   lambdaClient
} = require("..libs/lambdaClient.js");

// Instantiate an Lambda client service object.
const lambda = new LambdaClient({ region: REGION });

// Set the parameters.
const params = {
  Code: {
    S3Bucket: "BUCKET_NAME", // BUCKET_NAME
    S3Key: "ZIP_FILE_NAME", // ZIP_FILE_NAME
  },
  FunctionName: "LAMBDA_FUNCTION_NAME",
  Handler: "index.handler",
  Role: "IAM_ROLE_ARN", // IAM_ROLE_ARN; e.g., arn:aws:iam::650138640062:role/v3-lambda-tutorial-lambda-role
  Runtime: "nodejs12.x",
  Description:
    "Scans a DynamoDB table of employee details and using Amazon Simple Notification Services (Amazon SNS) to " +
    "send employees an email the each anniversary of their start-date.",
};

const run = async () => {
  try {
    const data = await lambda.send(new CreateFunctionCommand(params));
    console.log("Success", data); // successful response
  } catch (err) {
    console.log("Error", err); // an error occurred
  }
};
run();
```

명령줄에 다음을 입력하여 Lambda 함수를 배포합니다.

```
node lambda-function-setup.js
```

이 코드 예는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/src/helper-functions/lambda-function-setup.js) 제공합니다.

## Lambda 함수를 간접적으로 호출하도록 CloudWatch 구성
<a name="scheduled-events-invoking-lambda-run"></a>

Lambda 함수를 간접적으로 호출하도록 CloudWatch를 구성하려면 다음을 수행합니다.

1. Lambda 콘솔에서 **함수 페이지**를 엽니다.

1. Lambda 함수를 선택합니다.

1. **Designer**에서 **트리거 추가**를 선택합니다.

1. 트리거 유형을 **CloudWatch Events/EventBridge**로 설정합니다.

1. 규칙에서 **새 규칙 생성**을 선택합니다.

1.  규칙 이름과 규칙 설명을 입력합니다.

1. 규칙 유형에서 **예약 표현식**을 선택합니다.

1. **예약 표현식** 필드에 cron 표현식을 입력합니다. 예를 들어 **cron(0 12 ? \$1 MON-FRI \$1)**를 입력합니다.

1. **추가**를 선택합니다.
**참고**  
자세한 내용은 [Amazon EventBridge에 AWS Lambda 사용(CloudWatch Events)](https://docs.aws.amazon.com/lambda/latest/dg/services-cloudwatchevents.html) 단원을 참조하세요.

## 리소스 삭제
<a name="scheduled-events-invoking-lambda-destroy"></a>

축하합니다\$1 AWS SDK for JavaScript를 사용하여 Amazon CloudWatch 예약 이벤트를 통해 Lambda 함수를 간접적으로 호출했습니다. 이 자습서의 시작 부분에서 설명한 것처럼 요금이 부과되지 않도록 하려면 이 자습서를 진행하는 동안 생성한 모든 리소스를 종료해야 합니다. 다음과 같이이 자습서의 [AWS 리소스 생성](#scheduled-events-invoking-lambda-provision-resources) 주제에서 생성한 CloudFormation 스택을 삭제하여이 작업을 수행할 수 있습니다.

1. [CloudFormation 콘솔]( https://console.aws.amazon.com/cloudformation/home)을 엽니다.

1. **스택** 페이지에서 스택을 선택합니다.

1. **삭제**를 선택합니다.

# Amazon Lex 챗봇 빌드
<a name="lex-bot-example"></a>

웹 애플리케이션 내에 Amazon Lex 챗봇을 생성하여 웹 사이트 방문자의 참여를 유도할 수 있습니다. Amazon Lex 챗봇은 사람과 직접 접촉하지 않고도 사용자와 온라인 채팅 대화를 수행하는 기능입니다. 예를 들어 다음 그림은 호텔 객실 예약과 관련하여 사용자의 참여를 유도하는 Amazon Lex 챗봇을 보여줍니다.

![\[Chatbot interface demonstrating a hotel booking conversation with user inputs and bot responses.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/chatintro.png)


이 AWS 자습서에서 생성된 Amazon Lex 챗봇은 여러 언어를 처리할 수 있습니다. 예를 들어 프랑스어를 구사하는 사용자는 프랑스어 텍스트를 입력하고 프랑스어로 응답을 받을 수 있습니다.

![\[Chatbot interface demonstrating Amazon Lex integration with French language support.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot2.png)


마찬가지로, 사용자는 이탈리아어로 Amazon Lex 챗봇과 소통할 수 있습니다.

![\[Chat interface showing Italian language exchange between user and Amazon Lex chatbot.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/LanChatBot3.png)


이 AWS 자습서에서는 Amazon Lex 챗봇을 생성하고 이를 Node.js 웹 애플리케이션에 통합하는 방법을 안내합니다. AWS SDK for JavaScript (v3)는 다음 AWS 서비스를 호출하는 데 사용됩니다.
+ Amazon Lex
+ Amazon Comprehend
+ Amazon Translate

**완료 비용:**이 문서에 포함된 AWS 서비스는 [AWS 프리 티어](https://aws.amazon.com/free/?all-free-tier.sort-by=item.additionalFields.SortRank&all-free-tier.sort-order=asc)에 포함됩니다.

**참고:** 요금이 부과되지 않도록 하려면 이 자습서를 진행하는 동안 생성한 모든 리소스를 종료해야 합니다.

**앱을 빌드하려면 다음을 수행합니다.**

1. [사전 조건](#lex-bot-example-prerequisites)

1. [리소스를 프로비저닝합니다.](#lex-bot-provision-resources)

1. [Amazon Lex 챗봇 생성](#lex-bot-example-create-lex-bot)

1. [HTML 생성](#lex-bot-example-html)

1. [브라우저 스크립트 생성](#lex-bot-example-script)

1. [다음 단계](#lex-bot-example-next-steps)

## 사전 조건
<a name="lex-bot-example-prerequisites"></a>

이 예제를 설정하고 실행하려면 먼저 이러한 작업들을 완료해야 합니다.
+ 이러한 노드 TypeScript 예제를 실행하도록 프로젝트 환경을 설정하고 필요한 AWS SDK for JavaScript 모듈과 타사 모듈을 설치합니다. [GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-scheduled-events/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) 단원을 참조하세요.

## AWS 리소스 생성
<a name="lex-bot-provision-resources"></a>

이 자습서를 시작하려면 다음 리소스가 필요합니다.
+ 다음에 대한 권한이 연결된 미인증 IAM 역할:
  + Amazon Comprehend
  + Amazon Translate
  + Amazon Lex

이 리소스를 수동으로 생성할 수 있지만이 자습서에 설명된 AWS CloudFormation 대로를 사용하여 이러한 리소스를 프로비저닝하는 것이 좋습니다.

### 를 사용하여 AWS 리소스 생성 CloudFormation
<a name="lex-bot-example-resources-cli"></a>

CloudFormation 를 사용하면 AWS 인프라 배포를 예측 가능하고 반복적으로 생성하고 프로비저닝할 수 있습니다. 에 대한 자세한 내용은 [AWS CloudFormation 사용 설명서를](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/) CloudFormation참조하세요.

를 사용하여 CloudFormation 스택을 생성하려면 AWS CLI:

1. [AWS CLI 사용 설명서](https://docs.aws.amazon.com/cli/latest/userguide/cli-chap-welcome.html)의 AWS CLI 지침에 따라를 설치하고 구성합니다.

1. 프로젝트 폴더의 루트 디렉터리에 이름이 `setup.yaml`인 파일을 생성하고 [여기 GitHub의](https://github.com/awsdocs/aws-doc-sdk-examples/blob/main/javascriptv3/example_code/cross-services/lex-bot/setup.yaml) 내용을 해당 파일에 복사합니다.
**참고**  
 CloudFormation 템플릿은 [ GitHub에서 사용할](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk/lex_bot_example_iam_unauth_role) 수 있는를 AWS CDK 사용하여 생성되었습니다. 에 대한 자세한 내용은 [AWS Cloud Development Kit (AWS CDK) 개발자 안내서](https://docs.aws.amazon.com/cdk/latest/guide/)를 AWS CDK참조하세요.

1. 명령줄에서 다음 명령을 실행하여 *STACK\$1NAME*을 스택의 고유한 이름으로 바꿉니다.
**중요**  
스택 이름은 AWS 리전 및 AWS 계정 내에서 고유해야 합니다. 최대 128자까지 지정할 수 있으며 숫자와 하이픈을 사용할 수 있습니다.

   ```
   aws cloudformation create-stack --stack-name STACK_NAME --template-body file://setup.yaml --capabilities CAPABILITY_IAM
   ```

   `create-stack` 명령 파라미터에 대한 자세한 내용은 [AWS CLI 명령 참조 가이드](https://docs.aws.amazon.com/cli/latest/reference/cloudformation/create-stack.html) 및 [CloudFormation 사용 설명서](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/using-cfn-cli-creating-stack.html)를 참조하세요.

   생성된 리소스를 보려면 Amazon Lex 콘솔을 열고 스택을 선택한 다음, **리소스** 탭을 선택합니다.

## Amazon Lex 봇 생성
<a name="lex-bot-example-create-lex-bot"></a>

**중요**  
Amazon Lex 콘솔 V1을 사용하여 봇을 생성합니다. 이 예는 V2를 사용하여 생성된 봇에서는 작동하지 않습니다.

첫 번째 단계는 Amazon Web Services Management Console을 사용하여 Amazon Lex 챗봇을 생성하는 것입니다. 이 예에서는 Amazon Lex **BookTrip** 예가 사용됩니다. 자세한 내용은 [Book Trip](https://docs.aws.amazon.com/lex/latest/dg/ex-book-trip.html) 단원을 참조하세요.
+ Amazon Web Services Management Console에 로그인하고 [Amazon Web Services 콘솔](https://console.aws.amazon.com/lex/)에서 Amazon Lex 콘솔을 엽니다.
+ 봇 페이지에서 **생성**을 선택합니다.
+ **BookTrip** 청사진을 선택합니다(기본 봇 이름인 **BookTrip**을 그대로 유지).  
![\[Interface for creating a chatbot, showing BookTrip sample with conversation flow and components.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/pic2.png)
+ 기본 설정을 입력하고 **생성**을 선택합니다(콘솔에 **BookTrip** 봇이 표시됨). 편집기 탭에서 미리 구성된 intent의 세부 정보를 검토합니다.
+ 테스트 창에서 봇을 테스트합니다. *호텔 객실을 예약하고 싶어요*를 입력해 테스트를 시작합니다.  
![\[Chat interface showing a hotel booking conversation with a bot asking for the city.\]](http://docs.aws.amazon.com/ko_kr/sdk-for-javascript/v3/developer-guide/images/lex_example/ChatBotTest.png)
+ **게시**를 선택하고 별칭 이름을 지정합니다( 사용 시이 값이 필요함 AWS SDK for JavaScript).

**참고**  
 JavaScript 코드에서 **봇 이름**과 **봇 별칭**을 참조해야 합니다.

## HTML 생성
<a name="lex-bot-example-html"></a>

`index.html`이라는 이름의 파일을 만듭니다. 아래 코드를 복사하여 `index.html`에 붙여 넣습니다. 이 HTML은 `main.js`를 참조합니다. 이는 필수 AWS SDK for JavaScript 모듈을 포함하는 index.js의 번들 버전입니다. [HTML 생성](#lex-bot-example-html)에서 이 파일을 생성합니다. 또한 `index.html`은 스타일을 추가하는 `style.css`도 참조합니다.

```
<!doctype html>
<head>
  <title>Amazon Lex - Sample Application (BookTrip)</title>
  <link type="text/css" rel="stylesheet" href="style.css" />
</head>

<body>
  <h1 id="title">Amazon Lex - BookTrip</h1>
  <p id="intro">
    This multiple language chatbot shows you how easy it is to incorporate
    <a
      href="https://aws.amazon.com/lex/"
      title="Amazon Lex (product)"
      target="_new"
      >Amazon Lex</a
    >
    into your web apps. Try it out.
  </p>
  <div id="conversation"></div>
  <input
    type="text"
    id="wisdom"
    size="80"
    value=""
    placeholder="J'ai besoin d'une chambre d'hôtel"
  />
  <br />
  <button onclick="createResponse()">Send Text</button>
  <script type="text/javascript" src="./main.js"></script>
</body>
```

이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/resources/cdk#running-a-cdk-app)도 제공합니다.

## 브라우저 스크립트 생성
<a name="lex-bot-example-script"></a>

`index.js`이라는 이름의 파일을 만듭니다. 아래 코드를 복사하여 `index.js`에 붙여 넣습니다. 필요한 AWS SDK for JavaScript 모듈과 명령을 가져옵니다. Amazon Lex, Amazon Comprehend 및 Amazon Translate용 클라이언트를 생성합니다. *REGION*을 AWS 리전으로 바꾸고 *IDENTITY\$1POOL\$1ID*를에서 생성한 자격 증명 풀의 ID로 바꿉니다[AWS 리소스 생성](#lex-bot-provision-resources). 이 자격 증명 풀 ID를 검색하려면 Amazon Cognito 콘솔에서 자격 증명 풀을 열고 **자격 증명 풀 편집**을 선택한 다음, 측면 메뉴에서 **샘플 코드**를 선택합니다. 자격 증명 풀 ID는 콘솔에 빨간색 텍스트로 표시됩니다.

먼저, `libs` 디렉터리를 생성하고, `comprehendClient.js`, `lexClient.js`, `translateClient.js`라는 세 가지 파일을 생성하여 필수 서비스 클라이언트 객체를 생성합니다. 아래의 적절한 코드를 각 파일에 붙여 넣고 각 파일의 *REGION* 및 *IDENTITY\$1POOL\$1ID*를 바꿉니다.

**참고**  
[를 사용하여 AWS 리소스 생성 CloudFormation](#lex-bot-example-resources-cli)에서 생성한 Amazon Cognito 자격 증명 풀 ID를 사용하세요.

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { ComprehendClient } from "@aws-sdk/client-comprehend";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Comprehend service client object.
const comprehendClient = new ComprehendClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { comprehendClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { LexRuntimeServiceClient } from "@aws-sdk/client-lex-runtime-service";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Lex service client object.
const lexClient = new LexRuntimeServiceClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { lexClient };
```

```
import { CognitoIdentityClient } from "@aws-sdk/client-cognito-identity";
import { fromCognitoIdentityPool } from "@aws-sdk/credential-provider-cognito-identity";
import { TranslateClient } from "@aws-sdk/client-translate";

const REGION = "REGION";
const IDENTITY_POOL_ID = "IDENTITY_POOL_ID"; // An Amazon Cognito Identity Pool ID.

// Create an Amazon Translate service client object.
const translateClient = new TranslateClient({
  region: REGION,
  credentials: fromCognitoIdentityPool({
    client: new CognitoIdentityClient({ region: REGION }),
    identityPoolId: IDENTITY_POOL_ID,
  }),
});

export { translateClient };
```

이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/libs) 제공합니다.

다음으로, `index.js` 파일을 생성하고 아래 코드를 이 파일에 붙여 넣습니다.

 *BOT\$1ALIAS* 및 *BOT\$1NAME*을 각각 Amazon Lex 봇의 별칭 및 이름으로 바꾸고, *USER\$1ID*를 사용자 ID로 바꿉니다. `createResponse` 비동기 함수는 다음을 수행합니다.
+ 사용자가 입력한 텍스트를 브라우저에 가져오고 Amazon Comprehend를 사용하여 언어 코드를 결정합니다.
+ 언어 코드를 가져오고 Amazon Translate를 사용하여 텍스트를 영어로 번역합니다.
+ 번역된 텍스트를 가져오고 Amazon Lex를 사용하여 응답을 생성합니다.
+ 브라우저 페이지에 응답을 게시합니다.

```
import { DetectDominantLanguageCommand } from "@aws-sdk/client-comprehend";
import { TranslateTextCommand } from "@aws-sdk/client-translate";
import { PostTextCommand } from "@aws-sdk/client-lex-runtime-service";
import { lexClient } from "./libs/lexClient.js";
import { translateClient } from "./libs/translateClient.js";
import { comprehendClient } from "./libs/comprehendClient.js";

let g_text = "";
// Set the focus to the input box.
document.getElementById("wisdom").focus();

function showRequest() {
  const conversationDiv = document.getElementById("conversation");
  const requestPara = document.createElement("P");
  requestPara.className = "userRequest";
  requestPara.appendChild(document.createTextNode(g_text));
  conversationDiv.appendChild(requestPara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function showResponse(lexResponse) {
  const conversationDiv = document.getElementById("conversation");
  const responsePara = document.createElement("P");
  responsePara.className = "lexResponse";

  const lexTextResponse = lexResponse;

  responsePara.appendChild(document.createTextNode(lexTextResponse));
  responsePara.appendChild(document.createElement("br"));
  conversationDiv.appendChild(responsePara);
  conversationDiv.scrollTop = conversationDiv.scrollHeight;
}

function handletext(text) {
  g_text = text;
  const xhr = new XMLHttpRequest();
  xhr.addEventListener("load", loadNewItems, false);
  xhr.open("POST", "../text", true); // A Spring MVC controller
  xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); //necessary
  xhr.send(`text=${text}`);
}

function loadNewItems() {
  showRequest();

  // Re-enable input.
  const wisdomText = document.getElementById("wisdom");
  wisdomText.value = "";
  wisdomText.locked = false;
}

// Respond to user's input.
const createResponse = async () => {
  // Confirm there is text to submit.
  const wisdomText = document.getElementById("wisdom");
  if (wisdomText?.value && wisdomText.value.trim().length > 0) {
    // Disable input to show it is being sent.
    const wisdom = wisdomText.value.trim();
    wisdomText.value = "...";
    wisdomText.locked = true;
    handletext(wisdom);

    const comprehendParams = {
      Text: wisdom,
    };
    try {
      const data = await comprehendClient.send(
        new DetectDominantLanguageCommand(comprehendParams),
      );
      console.log(
        "Success. The language code is: ",
        data.Languages[0].LanguageCode,
      );
      const translateParams = {
        SourceLanguageCode: data.Languages[0].LanguageCode,
        TargetLanguageCode: "en", // For example, "en" for English.
        Text: wisdom,
      };
      try {
        const data = await translateClient.send(
          new TranslateTextCommand(translateParams),
        );
        console.log("Success. Translated text: ", data.TranslatedText);
        const lexParams = {
          botName: "BookTrip",
          botAlias: "mynewalias",
          inputText: data.TranslatedText,
          userId: "chatbot", // For example, 'chatbot-demo'.
        };
        try {
          const data = await lexClient.send(new PostTextCommand(lexParams));
          console.log("Success. Response is: ", data.message);
          const msg = data.message;
          showResponse(msg);
        } catch (err) {
          console.log("Error responding to message. ", err);
        }
      } catch (err) {
        console.log("Error translating text. ", err);
      }
    } catch (err) {
      console.log("Error identifying language. ", err);
    }
  }
};
// Make the function available to the browser.
window.createResponse = createResponse;
```

이 코드는 [여기 GitHub에서](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lex-bot/src/index.html) 제공합니다.

이제 Webpack을 사용하여 `index.js` 및 AWS SDK for JavaScript 모듈을 단일 파일 로 번들링합니다`main.js`.

1. webpack을 아직 설치하지 않았다면 이 예의 [사전 조건](#lex-bot-example-prerequisites)에 따라 설치합니다.
**참고**  
*Webpack*에 관한 자세한 내용은 [Webpack으로 애플리케이션 번들링](webpack.md) 단원을 참조하세요.

1. 명령줄에서 다음을 실행하여 이 예의 JavaScript를 `main.js`라는 파일로 번들링합니다.

   ```
   webpack index.js --mode development --target web --devtool false -o main.js
   ```

## 다음 단계
<a name="lex-bot-example-next-steps"></a>

축하합니다\$1 Amazon Lex를 사용하여 대화형 사용자 환경을 생성하는 Node.js 애플리케이션을 생성했습니다. 이 자습서의 시작 부분에서 설명한 것처럼 요금이 부과되지 않도록 하려면 이 자습서를 진행하는 동안 생성한 모든 리소스를 종료해야 합니다. 다음과 같이이 자습서의 [AWS 리소스 생성](#lex-bot-provision-resources) 주제에서 생성한 CloudFormation 스택을 삭제하여이 작업을 수행할 수 있습니다.

1. [CloudFormation 콘솔]( https://console.aws.amazon.com/cloudformation/home)을 엽니다.

1. **스택** 페이지에서 스택을 선택합니다.

1. **삭제**를 선택합니다.

더 많은 AWS 교차 서비스 예제는 [AWS SDK for JavaScript 교차 서비스 예제를 참조하세요](https://docs.aws.amazon.com/sdk-for-javascript/v3/developer-guide/tutorials.html).