使用 API Gateway 叫用 Lambda - AWS SDK for JavaScript

AWS SDK for JavaScript V3 API參考指南詳細描述 AWS SDK for JavaScript 第 3 版 (V3) 的所有API操作。

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

使用 API Gateway 叫用 Lambda

您可以使用 Amazon Gateway 來叫用 Lambda 函數,Amazon API Gateway 是用於建立、發佈HTTP、維護、監控和大規模保護 REST、 和 WebSocket APIs AWS 的服務。API 開發人員可以建立APIs該存取 AWS 或其他 Web 服務,以及儲存在 AWS Cloud 中的資料。身為 API Gateway 開發人員,您可以建立 APIs,以用於您自己的用戶端應用程式。如需詳細資訊,請參閱什麼是 Amazon API Gateway。

AWS Lambda 是一種運算服務,可讓您執行程式碼,而無需佈建或管理伺服器。您可以使用各種程式設計語言建立 Lambda 函數。如需 的詳細資訊 AWS Lambda,請參閱什麼是 AWS Lambda

在此範例中,您可以使用 Lambda JavaScript 執行期 來建立 Lambda 函數API。此範例會叫用不同的 AWS 服務來執行特定的使用案例。例如,假設組織向其員工傳送行動簡訊,祝賀他們在一年週年紀念日,如本圖所示。

DynamoDB 表

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

此範例示範如何使用 JavaScript 邏輯來建立執行此使用案例的解決方案。例如,您將了解如何讀取資料庫,以判斷哪些員工已達到一年周年日期、如何處理資料,以及使用 Lambda 函數傳送所有簡訊。然後,您將了解如何使用 API Gateway 來使用 Rest 端點來叫用此 AWS Lambda 函數。例如,您可以使用此 curl 命令叫用 Lambda 函數:

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

本 AWS 教學課程使用名為員工且包含這些欄位的 Amazon DynamoDB 資料表。

  • ID - 資料表的主要索引鍵。

  • firstName - 員工的名字。

  • 電話 - 員工的電話號碼。

  • startDate - 員工的開始日期。

DynamoDB 表
重要

完成成本:本文件中包含 AWS 的服務包含在 AWS 免費方案中。不過,在完成此範例之後,請務必終止所有資源,以確保不會向您收費。

先決條件任務

若要設定和執行此範例,您必須先完成這些任務:

  • 設定專案環境以執行這些節點 TypeScript 範例,並安裝必要的 AWS SDK for JavaScript 第三方模組。請遵循 上的指示 GitHub

  • 透過使用者登入資料建立共用組態檔。如需提供共用憑證檔案的詳細資訊,請參閱 和 AWS SDKs 工具參考指南 中的共用組態和憑證檔案

建立 AWS 資源

本教學課程需要下列資源:

  • 名為 的 Amazon DynamoDB 資料表Employee,具有名為 的索引鍵,Id以及上圖中顯示的欄位。請確定您輸入正確的資料,包括您要測試此使用案例的有效行動電話。如需詳細資訊,請參閱建立資料表

  • 具有連接許可IAM的角色,可執行 Lambda 函數。

  • 用於託管 Lambda 函數的 Amazon S3 儲存貯體。

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

使用 建立 AWS 資源 AWS CloudFormation

AWS CloudFormation 可讓您以可預測且重複的方式建立和佈建 AWS 基礎設施部署。如需 的詳細資訊 AWS CloudFormation,請參閱 AWS CloudFormation 使用者指南

若要使用 建立 AWS CloudFormation 堆疊 AWS CLI:

  1. 安裝並設定使用者指南 中的 AWS CLI 下列指示AWS CLI

  2. 在專案資料夾的setup.yaml根目錄中建立名為 的檔案,並將此處 GitHub的內容複製到其中。

    注意

    AWS CloudFormation 範本是使用 AWS CDK 上可用的 GitHub產生。如需 的詳細資訊 AWS CDK,請參閱 AWS Cloud Development Kit (AWS CDK) 開發人員指南

  3. 從命令列執行下列命令,取代 STACK_NAME 堆疊的唯一名稱。

    重要

    堆疊名稱在 AWS 區域和 AWS 帳戶中必須是唯一的。您最多可以指定 128 個字元,允許使用數字和連字號。

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

    如需create-stack命令參數的詳細資訊,請參閱 AWS CLI 命令參考指南 AWS CloudFormation 使用者指南

  4. 接下來,按照程序 填入資料表填入資料表

填入資料表

若要填入資料表,請先建立名為 的目錄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取得。

接下來,在專案資料夾的populate-table.js根目錄中建立名為 的檔案,並將此處 GitHub的內容複製到其中。對於其中一個項目,請將 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取得。

建立 AWS Lambda 函數

設定 SDK

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

Replace (取代) REGION 區域 AWS 。此程式碼可於 此處 GitHub取得。

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

Replace (取代) REGION 區域 AWS 。此程式碼可於 此處 GitHub取得。

首先,匯入所需的 AWS SDK for JavaScript (v3) 模組和命令。然後計算今天的日期,並將其指派給 參數。第三,建立 的參數ScanCommand。Replace (取代) TABLE_NAME 您在此範例的 建立 AWS 資源 區段中建立的資料表名稱。

下列程式碼片段說明此步驟。(如需完整範例,請參閱綁定 Lambda 函數。)

"use strict"; 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 資料表

首先,建立名為 的非同步/等待函數sendText,以使用 Amazon SNS 發佈文字訊息PublishCommand。然後,新增try區塊模式,以掃描 DynamoDB 資料表,找出今天工作週年紀念的員工,然後呼叫 sendText函數來傳送簡訊給這些員工。如果發生錯誤,則會呼叫 catch 區塊。

下列程式碼片段說明此步驟。(如需完整範例,請參閱綁定 Lambda 函數。)

// 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)); data.Items.forEach(function (element) { 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 函數

本主題說明如何將 mylambdafunction.ts和此範例所需的 AWS SDK for JavaScript 模組綁定到名為 的綁定檔案中index.js

  1. 如果您尚未安裝,請遵循此範例先決條件任務的 來安裝 Webpack。

    注意

    如需有關 webpack 的資訊,請參閱 捆綁應用程序與網絡包

  2. 在命令列中執行下列動作,將此範例 JavaScript 的 綁定到名為 <index.js> 的檔案中:

    webpack mylambdafunction.ts --mode development --target node --devtool false --output-library-target umd -o index.js
    重要

    請注意,輸出名為 index.js。這是因為 Lambda 函數必須具有index.js處理常式才能運作。

  3. 將套件輸出檔案 壓縮index.js為名為 ZIP的檔案mylambdafunction.zip

  4. mylambdafunction.zip 上傳至您在本教學課程建立 AWS 資源 主題中建立的 Amazon S3 儲存貯體。

部署 Lambda 函數。

在專案根中,建立 lambda-function-setup.ts 檔案,並將下列內容貼到其中。

Replace (取代) BUCKET_NAME 使用您上傳 Lambda 函數ZIP版本的 Amazon S3 儲存貯體名稱。Replace (取代) ZIP_FILE_NAME 名稱為 Lambda 函數ZIP版本的名稱。Replace (取代) ROLE 您在本教學建立 AWS 資源 課程主題中所建立IAM角色的 Amazon Resource Number (ARN)。Replace (取代) LAMBDA_FUNCTION_NAME 具有 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取得。

設定API閘道以叫用 Lambda 函數

建立其餘 API

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

  1. 登入 Amazon API Gateway 主控台

  2. 在 Rest 下API,選擇建置

  3. 選取新的API

    DynamoDB 表
  4. 員工指定為API名稱並提供描述。

    DynamoDB 表
  5. 選擇建立 API

  6. 員工區段下選擇資源

    DynamoDB 表
  7. 在名稱欄位中,指定員工

  8. 選擇 Create Resource (建立資源)

  9. 動作下拉式清單中,選擇建立資源

    DynamoDB 表
  10. 選擇 /employees ,從動作 中選取建立方法,然後從 GET /employees 下方的下拉式功能表中選取 。選擇核取記號圖示。

    DynamoDB 表
  11. 選擇 Lambda 函數,然後輸入 mylambdafunction 作為 Lambda 函數名稱。選擇 Save (儲存)。

測試API閘道方法

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

DynamoDB 表

叫用 Lambda 函數後,您可以檢視日誌檔案以查看成功訊息。

部署API閘道方法

測試成功後,您可以從 Amazon API Gateway 主控台 部署 方法。

  1. 選擇取得

    DynamoDB 表
  2. 動作下拉式清單中,選取部署 API

    DynamoDB 表
  3. 填寫部署API表單,然後選擇部署

    DynamoDB 表
  4. 選擇 Save Changes (儲存變更)。

  5. 再次選擇取得,並注意URL變更。這是您可以用來叫用 Lambda URL 函數的叫用。

    DynamoDB 表

刪除資源

恭喜您!您已使用 透過 Amazon API Gateway 叫用 Lambda 函數 AWS SDK for JavaScript。如本教學課程開頭所述,請務必在進行本教學課程時終止您建立的所有資源,以確保不會向您收費。您可以刪除在本教學建立 AWS 資源 課程主題中建立的 AWS CloudFormation 堆疊來執行此操作,如下所示:

  1. AWS CloudFormation 在 AWS 管理主控台 中開啟

  2. 開啟堆疊頁面,然後選取堆疊。

  3. 選擇 Delete (刪除)