

 [適用於 JavaScript 的 AWS SDK V3 API 參考指南](https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/)詳細說明 第 3 版 適用於 JavaScript 的 AWS SDK (V3) 的所有 API 操作。

本文為英文版的機器翻譯版本，如內容有任何歧義或不一致之處，概以英文版為準。

# 使用 API Gateway 叫用 Lambda
<a name="api-gateway-invoking-lambda-example"></a>

您可以使用 Amazon API Gateway 叫用 Lambda 函數，這是一種大規模建立、發佈、維護、監控和保護 REST、HTTP 和 WebSocket APIs AWS 的服務。API 開發人員可以建立 APIs 來存取 AWS 或其他 Web 服務，以及存放在 AWS 雲端的資料。身為 API Gateway 開發人員，您可以建立 APIs以用於您自己的用戶端應用程式。如需詳細資訊，請參閱[什麼是 Amazon API Gateway](https://docs.aws.amazon.com/apigateway/latest/developerguide/welcome.html)。

AWS Lambda 是一種運算服務，可讓您執行程式碼，而無需佈建或管理伺服器。您可以使用各種程式設計語言建立 Lambda 函數。如需 的詳細資訊 AWS Lambda，請參閱[什麼是 AWS Lambda](https://docs.aws.amazon.com/lambda/latest/dg/welcome.html) 。

在此範例中，您會使用 Lambda JavaScript 執行時期 API 建立 Lambda 函式。此範例會叫用不同的 AWS 服務來執行特定的使用案例。例如，假設組織傳送行動文字訊息給在一年週年紀念日恭喜他們的員工，如下圖所示。

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


此範例大約需要 20 分鐘才能完成。

此範例說明如何使用 JavaScript 邏輯來建立執行此使用案例的解決方案。例如，您將了解如何讀取資料庫，以判斷哪些員工已達到一週年的日期、如何處理資料，以及使用 Lambda 函數傳送文字訊息。然後，您將了解如何使用 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** - 員工的名字。
+ **電話** - 員工的電話號碼。
+ **startDate** - 員工的開始日期。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/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>

若要設定和執行此範例，您必須先完成這些任務：
+ 設定專案環境以執行這些 Node TypeScript 範例，並安裝必要的 適用於 JavaScript 的 AWS SDK 和第三方模組。遵循[ GitHub](https://github.com/awsdocs/aws-doc-sdk-examples/tree/main/javascriptv3/example_code/cross-services/lambda-api-gateway/README.md) 上的指示。
+ 透過使用者登入資料建立共用組態檔。如需提供共用登入資料檔案的詳細資訊，請參閱 *AWS SDKs * [和工具參考指南中的共用組態和登入資料檔案](https://docs.aws.amazon.com/sdkref/latest/guide/file-format.html)。

## 建立 AWS 資源
<a name="api-gateway-invoking-lambda-provision-resources"></a>

本教學課程需要下列資源：
+ 名為 的 Amazon DynamoDB 資料表`Employee`，具有名為 的索引鍵`Id`和上圖中顯示的欄位。請務必輸入正確的資料，包括您要用來測試此使用案例的有效行動電話。如需詳細資訊，請參閱[建立資料表](https://docs.aws.amazon.com/amazondynamodb/latest/developerguide/getting-started-step-1.html)。
+ 具有連接許可的 IAM 角色，可執行 Lambda 函數。
+ 用於託管 Lambda 函數的 Amazon S3 儲存貯體。

您可以手動建立這些資源，但建議您 CloudFormation 如本教學所述，使用 佈建這些資源。

### 使用 建立 AWS 資源 CloudFormation
<a name="api-gateway-invoking-lambda-resources-cli"></a>

CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 CloudFormation，請參閱[AWS CloudFormation 《 使用者指南》](https://docs.aws.amazon.com/AWSCloudFormation/latest/UserGuide/)。

若要使用 建立 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 CDK，請參閱 [AWS Cloud Development Kit (AWS CDK) 開發人員指南](https://docs.aws.amazon.com/cdk/latest/guide/)。

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>

### 設定軟體開發套件
<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)。

首先，匯入必要的 適用於 JavaScript 的 AWS SDK (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>

首先，建立名為 的非同步/等待函數`sendText`，以使用 Amazon SNS 發佈文字訊息`PublishCommand`。然後，新增`try`區塊模式來掃描 DynamoDB 資料表，尋找今天工作週年紀念的員工，然後呼叫 `sendText`函數來傳送文字訊息給這些員工。如果發生錯誤，則會呼叫 `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`和必要 適用於 JavaScript 的 AWS SDK 模組綁定到稱為 的綁定檔案中`index.js`。

1. 如果您尚未安裝，請遵循此範例[先決條件任務](#api-gateway-invoking-lambda-prerequisites)的 來安裝 Webpack。
**注意**  
如需 *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`為名為 的 ZIP 檔案`mylambdafunction.zip`。

1. `mylambdafunction.zip` 上傳至您在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程主題中建立的 Amazon S3 儲存貯體。

## 部署 Lambda 函數。
<a name="api-gateway-invoking-lambda-deploy-function"></a>

在您專案的根目錄中，建立 `lambda-function-setup.ts` 檔案，並將以下內容貼入其中。

將 *BUCKET\$1NAME* 取代為您上傳 Lambda 函數 ZIP 版本的 Amazon S3 儲存貯體名稱。以您 Lambda 函數的 ZIP 版本名稱取代 *ZIP\$1FILE\$1NAME*。將 *ROLE* 取代為您在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程中建立之 IAM 角色的 Amazon Resource Number (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)。

## 設定 API Gateway 以叫用 Lambda 函數
<a name="api-gateway-invoking-lambda-run"></a>

**若要建置應用程式：**

1. [建立其餘 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)

### 建立其餘 API
<a name="api-gateway-invoking-lambda-run-create"></a>

您可以使用 API Gateway 主控台來建立 Lambda 函數的靜態端點。完成後，您就可以使用靜態呼叫叫用 Lambda 函數。



1. 登入 [Amazon API Gateway 主控台](https://console.aws.amazon.com/apigateway)。

1. 在 Rest API 下，選擇**建置**。

1. 選取**新增 API**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/PicNewAPI.png)

1. 指定**員工**做為 API 名稱，並提供描述。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picEmployeeAPI.png)

1. 選擇**建立 API**。

1. 在**員工**區段下選擇**資源**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picResources.png)

1. 在名稱欄位中，指定**員工**。

1. 選擇 **Create Resource (建立資源)**。

1. 從**動作**下拉式清單中，選擇**建立資源**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picCreateResources.png)

1. 選擇 **/employees**，從**動作**中選取**建立方法**，然後從 **/employees** 下方的下拉式功能表中選取 **GET**。選擇核取記號圖示。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGet.png)

1. 選擇 **Lambda 函數**，然後輸入 **mylambdafunction** 做為 Lambda 函數名稱。選擇**儲存**。

### 測試 API Gateway 方法
<a name="api-gateway-invoking-lambda-run-test"></a>

在教學課程中，您可以測試叫用 **mylambdafunction** Lambda 函數的 API Gateway 方法。若要測試 方法，請選擇**測試**，如下圖所示。

![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/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. 選擇**取得**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picGetDeploy.png)

1. 從**動作**下拉式清單中，選取**部署 API**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1. 填寫**部署 API** 表單，然後選擇**部署**。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picDeployMethod.png)

1.  選擇 **Save Changes** (儲存變更)。

1.  再次選擇**取得**，並注意 URL 變更。這是您可以用來叫用 Lambda 函數的叫用 URL。  
![\[DynamoDB 表\]](http://docs.aws.amazon.com/zh_tw/sdk-for-javascript/v3/developer-guide/images/apigateway_example/picURL2.png)

## 刪除資源
<a name="api-gateway-invoking-lambda-destroy"></a>

恭喜您！您已使用 透過 Amazon API Gateway 叫用 Lambda 函數 適用於 JavaScript 的 AWS SDK。如本教學課程開頭所述，請務必在進行本教學課程時終止您建立的所有資源，以確保不會向您收費。您可以刪除在本教學[建立 AWS 資源](#api-gateway-invoking-lambda-provision-resources)課程主題中建立的 CloudFormation 堆疊來執行此操作，如下所示：

1. [CloudFormation 在 AWS 管理主控台中]( https://console.aws.amazon.com/cloudformation/home)開啟 。

1. 開啟**堆疊**頁面，然後選取堆疊。

1. 選擇**刪除**。