文件 AWS SDK AWS 範例 SDK 儲存庫中有更多可用的
本文為英文版的機器翻譯版本,如內容有任何歧義或不一致之處,概以英文版為準。
使用 SDK for JavaScript (v3) 的 Lambda 範例
下列程式碼範例示範如何搭配 Lambda 使用 AWS SDK for JavaScript (v3) 來執行動作和實作常見案例。
基本概念是程式碼範例,示範如何在服務中執行基本操作。
Actions 是大型程式的程式碼摘錄,必須在內容中執行。雖然動作會示範如何呼叫個別服務函數,但您可以在相關案例中查看內容中的動作。
案例是程式碼範例,示範如何透過呼叫服務內的多個函數或與其他函數結合來完成特定任務 AWS 服務。
每個範例都包含完整原始程式碼的連結,您可以在其中找到如何在內容中設定和執行程式碼的指示。
開始使用
下列程式碼範例示範如何開始使用 Lambda。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 import { LambdaClient, paginateListFunctions } from "@aws-sdk/client-lambda"; const client = new LambdaClient({}); export const helloLambda = async () => { const paginator = paginateListFunctions({ client }, {}); const functions = []; for await (const page of paginator) { const funcNames = page.Functions.map((f) => f.FunctionName); functions.push(...funcNames); } console.log("Functions:"); console.log(functions.join("\n")); return functions; };
-
如需 API 詳細資訊,請參閱 ListFunctions AWS SDK for JavaScript 參考中的 API。
-
基本概念
以下程式碼範例顯示做法:
建立 IAM 角色和 Lambda 函數,然後上傳處理常式程式碼。
調用具有單一參數的函數並取得結果。
更新函數程式碼並使用環境變數進行設定。
調用具有新參數的函數並取得結果。顯示傳回的執行日誌。
列出您帳戶的函數,然後清理相關資源。
如需詳細資訊,請參閱使用主控台建立 Lambda 函數。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 建立 AWS Identity and Access Management (IAM) 角色,授予 Lambda 寫入日誌的許可。
logger.log(`Creating role (${NAME_ROLE_LAMBDA})...`); const response = await createRole(NAME_ROLE_LAMBDA); import { AttachRolePolicyCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} policyArn * @param {string} roleName */ export const attachRolePolicy = (policyArn, roleName) => { const command = new AttachRolePolicyCommand({ PolicyArn: policyArn, RoleName: roleName, }); return client.send(command); };
建立 Lambda 函數並上傳處理常式程式碼。
const createFunction = async (funcName, roleArn) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${funcName}.zip`); const command = new CreateFunctionCommand({ Code: { ZipFile: code }, FunctionName: funcName, Role: roleArn, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
調用具有單一參數的函數並取得結果。
const invoke = async (funcName, payload) => { const client = new LambdaClient({}); const command = new InvokeCommand({ FunctionName: funcName, Payload: JSON.stringify(payload), LogType: LogType.Tail, }); const { Payload, LogResult } = await client.send(command); const result = Buffer.from(Payload).toString(); const logs = Buffer.from(LogResult, "base64").toString(); return { logs, result }; };
更新函數程式碼並設定具有環境變數的 Lambda 環境。
const updateFunctionCode = async (funcName, newFunc) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${newFunc}.zip`); const command = new UpdateFunctionCodeCommand({ ZipFile: code, FunctionName: funcName, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); }; const updateFunctionConfiguration = (funcName) => { const client = new LambdaClient({}); const config = readFileSync(`${dirname}../functions/config.json`).toString(); const command = new UpdateFunctionConfigurationCommand({ ...JSON.parse(config), FunctionName: funcName, }); const result = client.send(command); waitForFunctionUpdated({ FunctionName: funcName }); return result; };
列出您帳戶的函數。
const listFunctions = () => { const client = new LambdaClient({}); const command = new ListFunctionsCommand({}); return client.send(command); };
刪除 IAM 角色和 Lambda 函數。
import { DeleteRoleCommand, IAMClient } from "@aws-sdk/client-iam"; const client = new IAMClient({}); /** * * @param {string} roleName */ export const deleteRole = (roleName) => { const command = new DeleteRoleCommand({ RoleName: roleName }); return client.send(command); }; /** * @param {string} funcName */ const deleteFunction = (funcName) => { const client = new LambdaClient({}); const command = new DeleteFunctionCommand({ FunctionName: funcName }); return client.send(command); };
-
如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考中的下列主題。
-
動作
下列程式碼範例示範如何使用 CreateFunction
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const createFunction = async (funcName, roleArn) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${funcName}.zip`); const command = new CreateFunctionCommand({ Code: { ZipFile: code }, FunctionName: funcName, Role: roleArn, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
-
如需 API 詳細資訊,請參閱 CreateFunction AWS SDK for JavaScript 參考中的 API。
-
下列程式碼範例示範如何使用 DeleteFunction
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 /** * @param {string} funcName */ const deleteFunction = (funcName) => { const client = new LambdaClient({}); const command = new DeleteFunctionCommand({ FunctionName: funcName }); return client.send(command); };
-
如需 API 詳細資訊,請參閱 DeleteFunction AWS SDK for JavaScript 參考中的 API。
-
下列程式碼範例示範如何使用 GetFunction
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const getFunction = (funcName) => { const client = new LambdaClient({}); const command = new GetFunctionCommand({ FunctionName: funcName }); return client.send(command); };
-
如需 API 詳細資訊,請參閱 GetFunction AWS SDK for JavaScript 參考中的 API。
-
下列程式碼範例示範如何使用 Invoke
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const invoke = async (funcName, payload) => { const client = new LambdaClient({}); const command = new InvokeCommand({ FunctionName: funcName, Payload: JSON.stringify(payload), LogType: LogType.Tail, }); const { Payload, LogResult } = await client.send(command); const result = Buffer.from(Payload).toString(); const logs = Buffer.from(LogResult, "base64").toString(); return { logs, result }; };
-
如需 API 詳細資訊,請參閱在 Word 參考中叫用。 AWS SDK for JavaScript API
-
下列程式碼範例示範如何使用 ListFunctions
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const listFunctions = () => { const client = new LambdaClient({}); const command = new ListFunctionsCommand({}); return client.send(command); };
-
如需 API 詳細資訊,請參閱 ListFunctions AWS SDK for JavaScript 參考中的 API。
-
下列程式碼範例示範如何使用 UpdateFunctionCode
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const updateFunctionCode = async (funcName, newFunc) => { const client = new LambdaClient({}); const code = await readFile(`${dirname}../functions/${newFunc}.zip`); const command = new UpdateFunctionCodeCommand({ ZipFile: code, FunctionName: funcName, Architectures: [Architecture.arm64], Handler: "index.handler", // Required when sending a .zip file PackageType: PackageType.Zip, // Required when sending a .zip file Runtime: Runtime.nodejs16x, // Required when sending a .zip file }); return client.send(command); };
-
如需 API 詳細資訊,請參閱 UpdateFunctionCode AWS SDK for JavaScript 參考中的 API。
-
下列程式碼範例示範如何使用 UpdateFunctionConfiguration
。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 const updateFunctionConfiguration = (funcName) => { const client = new LambdaClient({}); const config = readFileSync(`${dirname}../functions/config.json`).toString(); const command = new UpdateFunctionConfigurationCommand({ ...JSON.parse(config), FunctionName: funcName, }); const result = client.send(command); waitForFunctionUpdated({ FunctionName: funcName }); return result; };
-
如需 API 詳細資訊,請參閱 UpdateFunctionConfiguration AWS SDK for JavaScript 參考中的 API。
-
案例
下列程式碼範例示範如何使用 Lambda 函數自動確認已知的 Amazon Cognito 使用者。
設定使用者集區以呼叫
PreSignUp
觸發程序的 Lambda 函數。使用 Amazon Cognito 註冊使用者。
Lambda 函數會掃描 DynamoDB 資料表,並自動確認已知使用者。
以新使用者身分登入,然後清除資源。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在 AWS 程式碼範例儲存庫
中設定和執行。 設定互動式 "Scenario" 執行。 JavaScript (v3) 範例共用案例執行器,以簡化複雜的範例。完整的原始程式碼是 on GitHub。
import { AutoConfirm } from "./scenario-auto-confirm.js"; /** * The context is passed to every scenario. Scenario steps * will modify the context. */ const context = { errors: [], users: [ { UserName: "test_user_1", UserEmail: "test_email_1@example.com", }, { UserName: "test_user_2", UserEmail: "test_email_2@example.com", }, { UserName: "test_user_3", UserEmail: "test_email_3@example.com", }, ], }; /** * Three Scenarios are created for the workflow. A Scenario is an orchestration class * that simplifies running a series of steps. */ export const scenarios = { // Demonstrate automatically confirming known users in a database. "auto-confirm": AutoConfirm(context), }; // Call function if run directly import { fileURLToPath } from "node:url"; import { parseScenarioArgs } from "@aws-doc-sdk-examples/lib/scenario/index.js"; if (process.argv[1] === fileURLToPath(import.meta.url)) { parseScenarioArgs(scenarios, { name: "Cognito user pools and triggers", description: "Demonstrate how to use the AWS SDKs to customize Amazon Cognito authentication behavior.", }); }
此案例示範自動確認已知使用者。它會協調範例步驟。
import { wait } from "@aws-doc-sdk-examples/lib/utils/util-timers.js"; import { Scenario, ScenarioAction, ScenarioInput, ScenarioOutput, } from "@aws-doc-sdk-examples/lib/scenario/scenario.js"; import { getStackOutputs, logCleanUpReminder, promptForStackName, promptForStackRegion, skipWhenErrors, } from "./steps-common.js"; import { populateTable } from "./actions/dynamodb-actions.js"; import { addPreSignUpHandler, deleteUser, getUser, signIn, signUpUser, } from "./actions/cognito-actions.js"; import { getLatestLogStreamForLambda, getLogEvents, } from "./actions/cloudwatch-logs-actions.js"; /** * @typedef {{ * errors: Error[], * password: string, * users: { UserName: string, UserEmail: string }[], * selectedUser?: string, * stackName?: string, * stackRegion?: string, * token?: string, * confirmDeleteSignedInUser?: boolean, * TableName?: string, * UserPoolClientId?: string, * UserPoolId?: string, * UserPoolArn?: string, * AutoConfirmHandlerArn?: string, * AutoConfirmHandlerName?: string * }} State */ const greeting = new ScenarioOutput( "greeting", (/** @type {State} */ state) => `This demo will populate some users into the \ database created as part of the "${state.stackName}" stack. \ Then the autoConfirmHandler will be linked to the PreSignUp \ trigger from Cognito. Finally, you will choose a user to sign up.`, { skipWhen: skipWhenErrors }, ); const logPopulatingUsers = new ScenarioOutput( "logPopulatingUsers", "Populating the DynamoDB table with some users.", { skipWhenErrors: skipWhenErrors }, ); const logPopulatingUsersComplete = new ScenarioOutput( "logPopulatingUsersComplete", "Done populating users.", { skipWhen: skipWhenErrors }, ); const populateUsers = new ScenarioAction( "populateUsers", async (/** @type {State} */ state) => { const [_, err] = await populateTable({ region: state.stackRegion, tableName: state.TableName, items: state.users, }); if (err) { state.errors.push(err); } }, { skipWhen: skipWhenErrors, }, ); const logSetupSignUpTrigger = new ScenarioOutput( "logSetupSignUpTrigger", "Setting up the PreSignUp trigger for the Cognito User Pool.", { skipWhen: skipWhenErrors }, ); const setupSignUpTrigger = new ScenarioAction( "setupSignUpTrigger", async (/** @type {State} */ state) => { const [_, err] = await addPreSignUpHandler({ region: state.stackRegion, userPoolId: state.UserPoolId, handlerArn: state.AutoConfirmHandlerArn, }); if (err) { state.errors.push(err); } }, { skipWhen: skipWhenErrors, }, ); const logSetupSignUpTriggerComplete = new ScenarioOutput( "logSetupSignUpTriggerComplete", ( /** @type {State} */ state, ) => `The lambda function "${state.AutoConfirmHandlerName}" \ has been configured as the PreSignUp trigger handler for the user pool "${state.UserPoolId}".`, { skipWhen: skipWhenErrors }, ); const selectUser = new ScenarioInput( "selectedUser", "Select a user to sign up.", { type: "select", choices: (/** @type {State} */ state) => state.users.map((u) => u.UserName), skipWhen: skipWhenErrors, default: (/** @type {State} */ state) => state.users[0].UserName, }, ); const checkIfUserAlreadyExists = new ScenarioAction( "checkIfUserAlreadyExists", async (/** @type {State} */ state) => { const [user, err] = await getUser({ region: state.stackRegion, userPoolId: state.UserPoolId, username: state.selectedUser, }); if (err?.name === "UserNotFoundException") { // Do nothing. We're not expecting the user to exist before // sign up is complete. return; } if (err) { state.errors.push(err); return; } if (user) { state.errors.push( new Error( `The user "${state.selectedUser}" already exists in the user pool "${state.UserPoolId}".`, ), ); } }, { skipWhen: skipWhenErrors, }, ); const createPassword = new ScenarioInput( "password", "Enter a password that has at least eight characters, uppercase, lowercase, numbers and symbols.", { type: "password", skipWhen: skipWhenErrors, default: "Abcd1234!" }, ); const logSignUpExistingUser = new ScenarioOutput( "logSignUpExistingUser", (/** @type {State} */ state) => `Signing up user "${state.selectedUser}".`, { skipWhen: skipWhenErrors }, ); const signUpExistingUser = new ScenarioAction( "signUpExistingUser", async (/** @type {State} */ state) => { const signUp = (password) => signUpUser({ region: state.stackRegion, userPoolClientId: state.UserPoolClientId, username: state.selectedUser, email: state.users.find((u) => u.UserName === state.selectedUser) .UserEmail, password, }); let [_, err] = await signUp(state.password); while (err?.name === "InvalidPasswordException") { console.warn("The password you entered was invalid."); await createPassword.handle(state); [_, err] = await signUp(state.password); } if (err) { state.errors.push(err); } }, { skipWhen: skipWhenErrors }, ); const logSignUpExistingUserComplete = new ScenarioOutput( "logSignUpExistingUserComplete", (/** @type {State} */ state) => `"${state.selectedUser} was signed up successfully.`, { skipWhen: skipWhenErrors }, ); const logLambdaLogs = new ScenarioAction( "logLambdaLogs", async (/** @type {State} */ state) => { console.log( "Waiting a few seconds to let Lambda write to CloudWatch Logs...\n", ); await wait(10); const [logStream, logStreamErr] = await getLatestLogStreamForLambda({ functionName: state.AutoConfirmHandlerName, region: state.stackRegion, }); if (logStreamErr) { state.errors.push(logStreamErr); return; } console.log( `Getting some recent events from log stream "${logStream.logStreamName}"`, ); const [logEvents, logEventsErr] = await getLogEvents({ functionName: state.AutoConfirmHandlerName, region: state.stackRegion, eventCount: 10, logStreamName: logStream.logStreamName, }); if (logEventsErr) { state.errors.push(logEventsErr); return; } console.log(logEvents.map((ev) => `\t${ev.message}`).join("")); }, { skipWhen: skipWhenErrors }, ); const logSignInUser = new ScenarioOutput( "logSignInUser", (/** @type {State} */ state) => `Let's sign in as ${state.selectedUser}`, { skipWhen: skipWhenErrors }, ); const signInUser = new ScenarioAction( "signInUser", async (/** @type {State} */ state) => { const [response, err] = await signIn({ region: state.stackRegion, clientId: state.UserPoolClientId, username: state.selectedUser, password: state.password, }); if (err?.name === "PasswordResetRequiredException") { state.errors.push(new Error("Please reset your password.")); return; } if (err) { state.errors.push(err); return; } state.token = response?.AuthenticationResult?.AccessToken; }, { skipWhen: skipWhenErrors }, ); const logSignInUserComplete = new ScenarioOutput( "logSignInUserComplete", (/** @type {State} */ state) => `Successfully signed in. Your access token starts with: ${state.token.slice(0, 11)}`, { skipWhen: skipWhenErrors }, ); const confirmDeleteSignedInUser = new ScenarioInput( "confirmDeleteSignedInUser", "Do you want to delete the currently signed in user?", { type: "confirm", skipWhen: skipWhenErrors }, ); const deleteSignedInUser = new ScenarioAction( "deleteSignedInUser", async (/** @type {State} */ state) => { const [_, err] = await deleteUser({ region: state.stackRegion, accessToken: state.token, }); if (err) { state.errors.push(err); } }, { skipWhen: (/** @type {State} */ state) => skipWhenErrors(state) || !state.confirmDeleteSignedInUser, }, ); const logErrors = new ScenarioOutput( "logErrors", (/** @type {State}*/ state) => { const errorList = state.errors .map((err) => ` - ${err.name}: ${err.message}`) .join("\n"); return `Scenario errors found:\n${errorList}`; }, { // Don't log errors when there aren't any! skipWhen: (/** @type {State} */ state) => state.errors.length === 0, }, ); export const AutoConfirm = (context) => new Scenario( "AutoConfirm", [ promptForStackName, promptForStackRegion, getStackOutputs, greeting, logPopulatingUsers, populateUsers, logPopulatingUsersComplete, logSetupSignUpTrigger, setupSignUpTrigger, logSetupSignUpTriggerComplete, selectUser, checkIfUserAlreadyExists, createPassword, logSignUpExistingUser, signUpExistingUser, logSignUpExistingUserComplete, logLambdaLogs, logSignInUser, signInUser, logSignInUserComplete, confirmDeleteSignedInUser, deleteSignedInUser, logCleanUpReminder, logErrors, ], context, );
這些是與其他案例共用的步驟。
import { ScenarioAction, ScenarioInput, ScenarioOutput, } from "@aws-doc-sdk-examples/lib/scenario/scenario.js"; import { getCfnOutputs } from "@aws-doc-sdk-examples/lib/sdk/cfn-outputs.js"; export const skipWhenErrors = (state) => state.errors.length > 0; export const getStackOutputs = new ScenarioAction( "getStackOutputs", async (state) => { if (!state.stackName || !state.stackRegion) { state.errors.push( new Error( "No stack name or region provided. The stack name and \ region are required to fetch CFN outputs relevant to this example.", ), ); return; } const outputs = await getCfnOutputs(state.stackName, state.stackRegion); Object.assign(state, outputs); }, ); export const promptForStackName = new ScenarioInput( "stackName", "Enter the name of the stack you deployed earlier.", { type: "input", default: "PoolsAndTriggersStack" }, ); export const promptForStackRegion = new ScenarioInput( "stackRegion", "Enter the region of the stack you deployed earlier.", { type: "input", default: "us-east-1" }, ); export const logCleanUpReminder = new ScenarioOutput( "logCleanUpReminder", "All done. Remember to run 'cdk destroy' to teardown the stack.", { skipWhen: skipWhenErrors }, );
具有 Lambda 函數之
PreSignUp
觸發程序的處理常式。import type { PreSignUpTriggerEvent, Handler } from "aws-lambda"; import type { UserRepository } from "./user-repository"; import { DynamoDBUserRepository } from "./user-repository"; export class PreSignUpHandler { private userRepository: UserRepository; constructor(userRepository: UserRepository) { this.userRepository = userRepository; } private isPreSignUpTriggerSource(event: PreSignUpTriggerEvent): boolean { return event.triggerSource === "PreSignUp_SignUp"; } private getEventUserEmail(event: PreSignUpTriggerEvent): string { return event.request.userAttributes.email; } async handlePreSignUpTriggerEvent( event: PreSignUpTriggerEvent, ): Promise<PreSignUpTriggerEvent> { console.log( `Received presignup from ${event.triggerSource} for user '${event.userName}'`, ); if (!this.isPreSignUpTriggerSource(event)) { return event; } const eventEmail = this.getEventUserEmail(event); console.log(`Looking up email ${eventEmail}.`); const storedUserInfo = await this.userRepository.getUserInfoByEmail(eventEmail); if (!storedUserInfo) { console.log( `Email ${eventEmail} not found. Email verification is required.`, ); return event; } if (storedUserInfo.UserName !== event.userName) { console.log( `UserEmail ${eventEmail} found, but stored UserName '${storedUserInfo.UserName}' does not match supplied UserName '${event.userName}'. Verification is required.`, ); } else { console.log( `UserEmail ${eventEmail} found with matching UserName ${storedUserInfo.UserName}. User is confirmed.`, ); event.response.autoConfirmUser = true; event.response.autoVerifyEmail = true; } return event; } } const createPreSignUpHandler = (): PreSignUpHandler => { const tableName = process.env.TABLE_NAME; if (!tableName) { throw new Error("TABLE_NAME environment variable is not set"); } const userRepository = new DynamoDBUserRepository(tableName); return new PreSignUpHandler(userRepository); }; export const handler: Handler = async (event: PreSignUpTriggerEvent) => { const preSignUpHandler = createPreSignUpHandler(); return preSignUpHandler.handlePreSignUpTriggerEvent(event); };
CloudWatch Logs 動作的模組。
import { CloudWatchLogsClient, GetLogEventsCommand, OrderBy, paginateDescribeLogStreams, } from "@aws-sdk/client-cloudwatch-logs"; /** * Get the latest log stream for a Lambda function. * @param {{ functionName: string, region: string }} config * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").LogStream | null, unknown]>} */ export const getLatestLogStreamForLambda = async ({ functionName, region }) => { try { const logGroupName = `/aws/lambda/${functionName}`; const cwlClient = new CloudWatchLogsClient({ region }); const paginator = paginateDescribeLogStreams( { client: cwlClient }, { descending: true, limit: 1, orderBy: OrderBy.LastEventTime, logGroupName, }, ); for await (const page of paginator) { return [page.logStreams[0], null]; } } catch (err) { return [null, err]; } }; /** * Get the log events for a Lambda function's log stream. * @param {{ * functionName: string, * logStreamName: string, * eventCount: number, * region: string * }} config * @returns {Promise<[import("@aws-sdk/client-cloudwatch-logs").OutputLogEvent[] | null, unknown]>} */ export const getLogEvents = async ({ functionName, logStreamName, eventCount, region, }) => { try { const cwlClient = new CloudWatchLogsClient({ region }); const logGroupName = `/aws/lambda/${functionName}`; const response = await cwlClient.send( new GetLogEventsCommand({ logStreamName: logStreamName, limit: eventCount, logGroupName: logGroupName, }), ); return [response.events, null]; } catch (err) { return [null, err]; } };
Amazon Cognito 動作的模組。
import { AdminGetUserCommand, CognitoIdentityProviderClient, DeleteUserCommand, InitiateAuthCommand, SignUpCommand, UpdateUserPoolCommand, } from "@aws-sdk/client-cognito-identity-provider"; /** * Connect a Lambda function to the PreSignUp trigger for a Cognito user pool * @param {{ region: string, userPoolId: string, handlerArn: string }} config * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").UpdateUserPoolCommandOutput | null, unknown]>} */ export const addPreSignUpHandler = async ({ region, userPoolId, handlerArn, }) => { try { const cognitoClient = new CognitoIdentityProviderClient({ region, }); const command = new UpdateUserPoolCommand({ UserPoolId: userPoolId, LambdaConfig: { PreSignUp: handlerArn, }, }); const response = await cognitoClient.send(command); return [response, null]; } catch (err) { return [null, err]; } }; /** * Attempt to register a user to a user pool with a given username and password. * @param {{ * region: string, * userPoolClientId: string, * username: string, * email: string, * password: string * }} config * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").SignUpCommandOutput | null, unknown]>} */ export const signUpUser = async ({ region, userPoolClientId, username, email, password, }) => { try { const cognitoClient = new CognitoIdentityProviderClient({ region, }); const response = await cognitoClient.send( new SignUpCommand({ ClientId: userPoolClientId, Username: username, Password: password, UserAttributes: [{ Name: "email", Value: email }], }), ); return [response, null]; } catch (err) { return [null, err]; } }; /** * Sign in a user to Amazon Cognito using a username and password authentication flow. * @param {{ region: string, clientId: string, username: string, password: string }} config * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").InitiateAuthCommandOutput | null, unknown]>} */ export const signIn = async ({ region, clientId, username, password }) => { try { const cognitoClient = new CognitoIdentityProviderClient({ region }); const response = await cognitoClient.send( new InitiateAuthCommand({ AuthFlow: "USER_PASSWORD_AUTH", ClientId: clientId, AuthParameters: { USERNAME: username, PASSWORD: password }, }), ); return [response, null]; } catch (err) { return [null, err]; } }; /** * Retrieve an existing user from a user pool. * @param {{ region: string, userPoolId: string, username: string }} config * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").AdminGetUserCommandOutput | null, unknown]>} */ export const getUser = async ({ region, userPoolId, username }) => { try { const cognitoClient = new CognitoIdentityProviderClient({ region }); const response = await cognitoClient.send( new AdminGetUserCommand({ UserPoolId: userPoolId, Username: username, }), ); return [response, null]; } catch (err) { return [null, err]; } }; /** * Delete the signed-in user. Useful for allowing a user to delete their * own profile. * @param {{ region: string, accessToken: string }} config * @returns {Promise<[import("@aws-sdk/client-cognito-identity-provider").DeleteUserCommandOutput | null, unknown]>} */ export const deleteUser = async ({ region, accessToken }) => { try { const client = new CognitoIdentityProviderClient({ region }); const response = await client.send( new DeleteUserCommand({ AccessToken: accessToken }), ); return [response, null]; } catch (err) { return [null, err]; } };
DynamoDB 動作的模組。
import { DynamoDBClient } from "@aws-sdk/client-dynamodb"; import { BatchWriteCommand, DynamoDBDocumentClient, } from "@aws-sdk/lib-dynamodb"; /** * Populate a DynamoDB table with provide items. * @param {{ region: string, tableName: string, items: Record<string, unknown>[] }} config * @returns {Promise<[import("@aws-sdk/lib-dynamodb").BatchWriteCommandOutput | null, unknown]>} */ export const populateTable = async ({ region, tableName, items }) => { try { const ddbClient = new DynamoDBClient({ region }); const docClient = DynamoDBDocumentClient.from(ddbClient); const response = await docClient.send( new BatchWriteCommand({ RequestItems: { [tableName]: items.map((item) => ({ PutRequest: { Item: item, }, })), }, }), ); return [response, null]; } catch (err) { return [null, err]; } };
-
如需 API 詳細資訊,請參閱 AWS SDK for JavaScript API 參考中的下列主題。
-
下列程式碼範例示範如何建立無伺服器應用程式,讓使用者以標籤管理相片。
下列程式碼範例會示範如何建立可分析客戶評論卡、從其原始語言進行翻譯、判斷對方情緒,以及透過翻譯後的文字產生音訊檔案的應用程式。
- SDK for JavaScript (v3)
-
此範例應用程式會分析和存儲客戶的意見回饋卡。具體來說,它滿足了紐約市一家虛構飯店的需求。飯店以實體評論卡的形式收到賓客以各種語言撰寫的意見回饋。這些意見回饋透過 Web 用戶端上傳至應用程式。評論卡的影像上傳後,系統會執行下列步驟:
-
文字內容是使用 Amazon Textract 從影像中擷取。
-
Amazon Comprehend 會決定擷取文字及其用語的情感。
-
擷取的文字內容會使用 Amazon Translate 翻譯成英文。
-
Amazon Polly 會使用擷取的文字內容合成音訊檔案。
完整的應用程式可透過 AWS CDK 部署。如需原始程式碼和部署指示,請參閱 GitHub
中的專案。下列摘錄顯示如何在 Lambda 函數內 AWS SDK for JavaScript 使用 。 import { ComprehendClient, DetectDominantLanguageCommand, DetectSentimentCommand, } from "@aws-sdk/client-comprehend"; /** * Determine the language and sentiment of the extracted text. * * @param {{ source_text: string}} extractTextOutput */ export const handler = async (extractTextOutput) => { const comprehendClient = new ComprehendClient({}); const detectDominantLanguageCommand = new DetectDominantLanguageCommand({ Text: extractTextOutput.source_text, }); // The source language is required for sentiment analysis and // translation in the next step. const { Languages } = await comprehendClient.send( detectDominantLanguageCommand, ); const languageCode = Languages[0].LanguageCode; const detectSentimentCommand = new DetectSentimentCommand({ Text: extractTextOutput.source_text, LanguageCode: languageCode, }); const { Sentiment } = await comprehendClient.send(detectSentimentCommand); return { sentiment: Sentiment, language_code: languageCode, }; };
import { DetectDocumentTextCommand, TextractClient, } from "@aws-sdk/client-textract"; /** * Fetch the S3 object from the event and analyze it using Amazon Textract. * * @param {import("@types/aws-lambda").EventBridgeEvent<"Object Created">} eventBridgeS3Event */ export const handler = async (eventBridgeS3Event) => { const textractClient = new TextractClient(); const detectDocumentTextCommand = new DetectDocumentTextCommand({ Document: { S3Object: { Bucket: eventBridgeS3Event.bucket, Name: eventBridgeS3Event.object, }, }, }); // Textract returns a list of blocks. A block can be a line, a page, word, etc. // Each block also contains geometry of the detected text. // For more information on the Block type, see https://docs.aws.amazon.com/textract/latest/dg/API_Block.html. const { Blocks } = await textractClient.send(detectDocumentTextCommand); // For the purpose of this example, we are only interested in words. const extractedWords = Blocks.filter((b) => b.BlockType === "WORD").map( (b) => b.Text, ); return extractedWords.join(" "); };
import { PollyClient, SynthesizeSpeechCommand } from "@aws-sdk/client-polly"; import { S3Client } from "@aws-sdk/client-s3"; import { Upload } from "@aws-sdk/lib-storage"; /** * Synthesize an audio file from text. * * @param {{ bucket: string, translated_text: string, object: string}} sourceDestinationConfig */ export const handler = async (sourceDestinationConfig) => { const pollyClient = new PollyClient({}); const synthesizeSpeechCommand = new SynthesizeSpeechCommand({ Engine: "neural", Text: sourceDestinationConfig.translated_text, VoiceId: "Ruth", OutputFormat: "mp3", }); const { AudioStream } = await pollyClient.send(synthesizeSpeechCommand); const audioKey = `${sourceDestinationConfig.object}.mp3`; // Store the audio file in S3. const s3Client = new S3Client(); const upload = new Upload({ client: s3Client, params: { Bucket: sourceDestinationConfig.bucket, Key: audioKey, Body: AudioStream, ContentType: "audio/mp3", }, }); await upload.done(); return audioKey; };
import { TranslateClient, TranslateTextCommand, } from "@aws-sdk/client-translate"; /** * Translate the extracted text to English. * * @param {{ extracted_text: string, source_language_code: string}} textAndSourceLanguage */ export const handler = async (textAndSourceLanguage) => { const translateClient = new TranslateClient({}); const translateCommand = new TranslateTextCommand({ SourceLanguageCode: textAndSourceLanguage.source_language_code, TargetLanguageCode: "en", Text: textAndSourceLanguage.extracted_text, }); const { TranslatedText } = await translateClient.send(translateCommand); return { translated_text: TranslatedText }; };
此範例中使用的服務
Amazon Comprehend
Lambda
Amazon Polly
Amazon Textract
Amazon Translate
-
下列程式碼範例示範如何從瀏覽器叫用 AWS Lambda 函數。
- SDK for JavaScript (v3)
-
您可以建立瀏覽器型應用程式,該應用程式使用 AWS Lambda 函數更新 Amazon DynamoDB 資料表,其中包含使用者選擇。此應用程式使用 AWS SDK for JavaScript v3。
如需完整的原始程式碼和如何設定和執行的指示,請參閱 GitHub
上的完整範例。 此範例中使用的服務
DynamoDB
Lambda
下列程式碼範例示範如何建立 Amazon API Gateway 調用的 AWS Lambda 函數。
- SDK for JavaScript (v3)
-
示範如何使用 Lambda JavaScript 執行期 API 建立 AWS Lambda 函數。此範例會叫用不同的 AWS 服務來執行特定使用案例。此範例示範如何建立由 Amazon API Gateway 調用的 Lambda 函數,以掃描工作週年紀念的 Amazon DynamoDB 資料表,並使用 Amazon Simple Notification Service (Amazon SNS) 傳送文字訊息給您的員工,在一年週年紀念日恭喜他們。
如需完整的原始程式碼和如何設定和執行的指示,請參閱 GitHub
上的完整範例。 此範例也可在 AWS SDK for JavaScript v3 開發人員指南中取得。
此範例中使用的服務
API Gateway
DynamoDB
Lambda
Amazon SNS
下列程式碼範例示範如何建立 Amazon EventBridge 排程事件調用的 AWS Lambda 函數。
- SDK for JavaScript (v3)
-
示範如何建立叫用 AWS Lambda 函數的 Amazon EventBridge 排程事件。Configure EventBridge 使用 Cron 表達式來排程 Lambda 函數的叫用時間。在此範例中,您可以使用 Lambda JavaScript 執行期 API 來建立 Lambda 函數。此範例會叫用不同的 AWS 服務來執行特定使用案例。此範例示範如何建立應用程式,將行動裝置文字訊息傳送給員工,在他們的週年紀念日向他們道賀。
如需完整的原始程式碼和如何設定和執行的指示,請參閱 GitHub
上的完整範例。 此範例也可在 AWS SDK for JavaScript v3 開發人員指南中取得。
此範例中使用的服務
DynamoDB
EventBridge
Lambda
Amazon SNS
無伺服器範例
下列程式碼範例示範如何實作連線至 RDS 資料庫的 Lambda 函數。函數會提出簡單的資料庫請求並傳回結果。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用RDS 連線至 Lambda 函數中的 Amazon JavaScript 資料庫。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 /* Node.js code here. */ // ES6+ example import { Signer } from "@aws-sdk/rds-signer"; import mysql from 'mysql2/promise'; async function createAuthToken() { // Define connection authentication parameters const dbinfo = { hostname: process.env.ProxyHostName, port: process.env.Port, username: process.env.DBUserName, region: process.env.AWS_REGION, } // Create RDS Signer object const signer = new Signer(dbinfo); // Request authorization token from RDS, specifying the username const token = await signer.getAuthToken(); return token; } async function dbOps() { // Obtain auth token const token = await createAuthToken(); // Define connection configuration let connectionConfig = { host: process.env.ProxyHostName, user: process.env.DBUserName, password: token, database: process.env.DBName, ssl: 'Amazon RDS' } // Create the connection to the DB const conn = await mysql.createConnection(connectionConfig); // Obtain the result of the query const [res,] = await conn.execute('select ?+? as sum', [3, 2]); return res; } export const handler = async (event) => { // Execute database flow const result = await dbOps(); // Return result return { statusCode: 200, body: JSON.stringify("The selected sum is: " + result[0].sum) } };
使用RDS 連線至 Lambda 函數中的 Amazon TypeScript 資料庫。
import { Signer } from "@aws-sdk/rds-signer"; import mysql from 'mysql2/promise'; // RDS settings // Using '!' (non-null assertion operator) to tell the TypeScript compiler that the DB settings are not null or undefined, const proxy_host_name = process.env.PROXY_HOST_NAME! const port = parseInt(process.env.PORT!) const db_name = process.env.DB_NAME! const db_user_name = process.env.DB_USER_NAME! const aws_region = process.env.AWS_REGION! async function createAuthToken(): Promise<string> { // Create RDS Signer object const signer = new Signer({ hostname: proxy_host_name, port: port, region: aws_region, username: db_user_name }); // Request authorization token from RDS, specifying the username const token = await signer.getAuthToken(); return token; } async function dbOps(): Promise<mysql.QueryResult | undefined> { try { // Obtain auth token const token = await createAuthToken(); const conn = await mysql.createConnection({ host: proxy_host_name, user: db_user_name, password: token, database: db_name, ssl: 'Amazon RDS' // Ensure you have the CA bundle for SSL connection }); const [rows, fields] = await conn.execute('SELECT ? + ? AS sum', [3, 2]); console.log('result:', rows); return rows; } catch (err) { console.log(err); } } export const lambdaHandler = async (event: any): Promise<{ statusCode: number; body: string }> => { // Execute database flow const result = await dbOps(); // Return error is result is undefined if (result == undefined) return { statusCode: 500, body: JSON.stringify(`Error with connection to DB host`) } // Return result return { statusCode: 200, body: JSON.stringify(`The selected sum is: ${result[0].sum}`) }; };
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Kinesis 串流接收記錄所觸發的事件。此函數會擷取 Kinesis 承載、從 Base64 解碼,並記錄記錄內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda using JavaScript 使用 Kinesis 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const record of event.Records) { try { console.log(`Processed Kinesis Event - EventID: ${record.eventID}`); const recordData = await getRecordDataAsync(record.kinesis); console.log(`Record Data: ${recordData}`); // TODO: Do interesting work based on the new data } catch (err) { console.error(`An error occurred ${err}`); throw err; } } console.log(`Successfully processed ${event.Records.length} records.`); }; async function getRecordDataAsync(payload) { var data = Buffer.from(payload.data, "base64").toString("utf-8"); await Promise.resolve(1); //Placeholder for actual async work return data; }
使用 Lambda using TypeScript 使用 Kinesis 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { KinesisStreamEvent, Context, KinesisStreamHandler, KinesisStreamRecordPayload, } from "aws-lambda"; import { Buffer } from "buffer"; import { Logger } from "@aws-lambda-powertools/logger"; const logger = new Logger({ logLevel: "INFO", serviceName: "kinesis-stream-handler-sample", }); export const functionHandler: KinesisStreamHandler = async ( event: KinesisStreamEvent, context: Context ): Promise<void> => { for (const record of event.Records) { try { logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`); const recordData = await getRecordDataAsync(record.kinesis); logger.info(`Record Data: ${recordData}`); // TODO: Do interesting work based on the new data } catch (err) { logger.error(`An error occurred ${err}`); throw err; } logger.info(`Successfully processed ${event.Records.length} records.`); } }; async function getRecordDataAsync( payload: KinesisStreamRecordPayload ): Promise<string> { var data = Buffer.from(payload.data, "base64").toString("utf-8"); await Promise.resolve(1); //Placeholder for actual async work return data; }
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 DynamoDB 串流接收記錄所觸發的事件。函數會擷取 DynamoDB 承載並記錄記錄內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda using JavaScript 使用 DynamoDB 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { console.log(JSON.stringify(event, null, 2)); event.Records.forEach(record => { logDynamoDBRecord(record); }); }; const logDynamoDBRecord = (record) => { console.log(record.eventID); console.log(record.eventName); console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); };
使用 Lambda using TypeScript 使用 DynamoDB 事件。
export const handler = async (event, context) => { console.log(JSON.stringify(event, null, 2)); event.Records.forEach(record => { logDynamoDBRecord(record); }); } const logDynamoDBRecord = (record) => { console.log(record.eventID); console.log(record.eventName); console.log(`DynamoDB Record: ${JSON.stringify(record.dynamodb)}`); };
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 DocumentDB 變更串流接收記錄所觸發的事件。函數會擷取 DocumentDB 承載並記錄記錄內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda using JavaScript 使用 Amazon DocumentDB 事件。
console.log('Loading function'); exports.handler = async (event, context) => { event.events.forEach(record => { logDocumentDBEvent(record); }); return 'OK'; }; const logDocumentDBEvent = (record) => { console.log('Operation type: ' + record.event.operationType); console.log('db: ' + record.event.ns.db); console.log('collection: ' + record.event.ns.coll); console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); };
使用 Lambda using TypeScript 使用 Amazon DocumentDB 事件
import { DocumentDBEventRecord, DocumentDBEventSubscriptionContext } from 'aws-lambda'; console.log('Loading function'); export const handler = async ( event: DocumentDBEventSubscriptionContext, context: any ): Promise<string> => { event.events.forEach((record: DocumentDBEventRecord) => { logDocumentDBEvent(record); }); return 'OK'; }; const logDocumentDBEvent = (record: DocumentDBEventRecord): void => { console.log('Operation type: ' + record.event.operationType); console.log('db: ' + record.event.ns.db); console.log('collection: ' + record.event.ns.coll); console.log('Full document:', JSON.stringify(record.event.fullDocument, null, 2)); };
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 Amazon MSK 叢集接收記錄所觸發的事件。函數會擷取 MSK 承載並記錄記錄內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda usingMSK 使用 Amazon JavaScript 事件。
exports.handler = async (event) => { // Iterate through keys for (let key in event.records) { console.log('Key: ', key) // Iterate through records event.records[key].map((record) => { console.log('Record: ', record) // Decode base64 const msg = Buffer.from(record.value, 'base64').toString() console.log('Message:', msg) }) } }
下列程式碼範例示範如何實作 Lambda 函數,該函數接收透過將物件上傳至 S3 儲存貯體所觸發的事件。函數會從事件參數擷取 S3 儲存貯體名稱和物件金鑰,並呼叫 Amazon S3 API 來擷取和記錄物件的內容類型。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda using JavaScript 取用 S3 事件。
import { S3Client, HeadObjectCommand } from "@aws-sdk/client-s3"; const client = new S3Client(); export const handler = async (event, context) => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); try { const { ContentType } = await client.send(new HeadObjectCommand({ Bucket: bucket, Key: key, })); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } };
使用 Lambda using TypeScript 取用 S3 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { S3Event } from 'aws-lambda'; import { S3Client, HeadObjectCommand } from '@aws-sdk/client-s3'; const s3 = new S3Client({ region: process.env.AWS_REGION }); export const handler = async (event: S3Event): Promise<string | undefined> => { // Get the object from the event and show its content type const bucket = event.Records[0].s3.bucket.name; const key = decodeURIComponent(event.Records[0].s3.object.key.replace(/\+/g, ' ')); const params = { Bucket: bucket, Key: key, }; try { const { ContentType } = await s3.send(new HeadObjectCommand(params)); console.log('CONTENT TYPE:', ContentType); return ContentType; } catch (err) { console.log(err); const message = `Error getting object ${key} from bucket ${bucket}. Make sure they exist and your bucket is in the same region as this function.`; console.log(message); throw new Error(message); } };
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 SNS 主題接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda usingSNS 使用 JavaScript 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record) { try { const message = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }
使用 Lambda usingSNS 使用 TypeScript 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SNSEvent, Context, SNSHandler, SNSEventRecord } from "aws-lambda"; export const functionHandler: SNSHandler = async ( event: SNSEvent, context: Context ): Promise<void> => { for (const record of event.Records) { await processMessageAsync(record); } console.info("done"); }; async function processMessageAsync(record: SNSEventRecord): Promise<any> { try { const message: string = JSON.stringify(record.Sns.Message); console.log(`Processed message ${message}`); await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }
下列程式碼範例示範如何實作 Lambda 函數,該函數接收從 SQS 佇列接收訊息所觸發的事件。函數會從事件參數擷取訊息,並記錄每一則訊息的內容。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda usingSQS 使用 JavaScript 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const message of event.Records) { await processMessageAsync(message); } console.info("done"); }; async function processMessageAsync(message) { try { console.log(`Processed message ${message.body}`); // TODO: Do interesting work based on the new message await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }
使用 Lambda usingSQS 使用 TypeScript 事件。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SQSEvent, Context, SQSHandler, SQSRecord } from "aws-lambda"; export const functionHandler: SQSHandler = async ( event: SQSEvent, context: Context ): Promise<void> => { for (const message of event.Records) { await processMessageAsync(message); } console.info("done"); }; async function processMessageAsync(message: SQSRecord): Promise<any> { try { console.log(`Processed message ${message.body}`); // TODO: Do interesting work based on the new message await Promise.resolve(1); //Placeholder for actual async work } catch (err) { console.error("An error occurred"); throw err; } }
下列程式碼範例示範如何針對從 Kinesis 串流接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Javascript 搭配 Lambda 報告 Kinesis 批次項目失敗。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 exports.handler = async (event, context) => { for (const record of event.Records) { try { console.log(`Processed Kinesis Event - EventID: ${record.eventID}`); const recordData = await getRecordDataAsync(record.kinesis); console.log(`Record Data: ${recordData}`); // TODO: Do interesting work based on the new data } catch (err) { console.error(`An error occurred ${err}`); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return { batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }], }; } } console.log(`Successfully processed ${event.Records.length} records.`); return { batchItemFailures: [] }; }; async function getRecordDataAsync(payload) { var data = Buffer.from(payload.data, "base64").toString("utf-8"); await Promise.resolve(1); //Placeholder for actual async work return data; }
使用 Lambda using TypeScript 報告 Kinesis 批次項目失敗。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { KinesisStreamEvent, Context, KinesisStreamHandler, KinesisStreamRecordPayload, KinesisStreamBatchResponse, } from "aws-lambda"; import { Buffer } from "buffer"; import { Logger } from "@aws-lambda-powertools/logger"; const logger = new Logger({ logLevel: "INFO", serviceName: "kinesis-stream-handler-sample", }); export const functionHandler: KinesisStreamHandler = async ( event: KinesisStreamEvent, context: Context ): Promise<KinesisStreamBatchResponse> => { for (const record of event.Records) { try { logger.info(`Processed Kinesis Event - EventID: ${record.eventID}`); const recordData = await getRecordDataAsync(record.kinesis); logger.info(`Record Data: ${recordData}`); // TODO: Do interesting work based on the new data } catch (err) { logger.error(`An error occurred ${err}`); /* Since we are working with streams, we can return the failed item immediately. Lambda will immediately begin to retry processing from this failed item onwards. */ return { batchItemFailures: [{ itemIdentifier: record.kinesis.sequenceNumber }], }; } } logger.info(`Successfully processed ${event.Records.length} records.`); return { batchItemFailures: [] }; }; async function getRecordDataAsync( payload: KinesisStreamRecordPayload ): Promise<string> { var data = Buffer.from(payload.data, "base64").toString("utf-8"); await Promise.resolve(1); //Placeholder for actual async work return data; }
下列程式碼範例示範如何針對從 DynamoDB 串流接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda using JavaScript 報告 DynamoDB 批次項目失敗。
export const handler = async (event) => { const records = event.Records; let curRecordSequenceNumber = ""; for (const record of records) { try { // Process your record curRecordSequenceNumber = record.dynamodb.SequenceNumber; } catch (e) { // Return failed record's sequence number return { batchItemFailures: [{ itemIdentifier: curRecordSequenceNumber }] }; } } return { batchItemFailures: [] }; };
使用 Lambda using TypeScript 報告 DynamoDB 批次項目失敗。
import { DynamoDBBatchResponse, DynamoDBBatchItemFailure, DynamoDBStreamEvent, } from "aws-lambda"; export const handler = async ( event: DynamoDBStreamEvent ): Promise<DynamoDBBatchResponse> => { const batchItemFailures: DynamoDBBatchItemFailure[] = []; let curRecordSequenceNumber; for (const record of event.Records) { curRecordSequenceNumber = record.dynamodb?.SequenceNumber; if (curRecordSequenceNumber) { batchItemFailures.push({ itemIdentifier: curRecordSequenceNumber, }); } } return { batchItemFailures: batchItemFailures }; };
下列程式碼範例示範如何針對從 SQS 佇列接收事件的 Lambda 函數實作部分批次回應。此函數會在回應中報告批次項目失敗,指示 Lambda 稍後重試這些訊息。
- SDK for JavaScript (v3)
-
注意
還有更多 on GitHub。尋找完整範例,並了解如何在無伺服器範例
儲存庫中設定和執行。 使用 Lambda usingSQS 報告 JavaScript 批次項目失敗。
// Node.js 20.x Lambda runtime, AWS SDK for Javascript V3 export const handler = async (event, context) => { const batchItemFailures = []; for (const record of event.Records) { try { await processMessageAsync(record, context); } catch (error) { batchItemFailures.push({ itemIdentifier: record.messageId }); } } return { batchItemFailures }; }; async function processMessageAsync(record, context) { if (record.body && record.body.includes("error")) { throw new Error("There is an error in the SQS Message."); } console.log(`Processed message: ${record.body}`); }
使用 Lambda usingSQS 報告 TypeScript 批次項目失敗。
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. // SPDX-License-Identifier: Apache-2.0 import { SQSEvent, SQSBatchResponse, Context, SQSBatchItemFailure, SQSRecord } from 'aws-lambda'; export const handler = async (event: SQSEvent, context: Context): Promise<SQSBatchResponse> => { const batchItemFailures: SQSBatchItemFailure[] = []; for (const record of event.Records) { try { await processMessageAsync(record); } catch (error) { batchItemFailures.push({ itemIdentifier: record.messageId }); } } return {batchItemFailures: batchItemFailures}; }; async function processMessageAsync(record: SQSRecord): Promise<void> { if (record.body && record.body.includes("error")) { throw new Error('There is an error in the SQS Message.'); } console.log(`Processed message ${record.body}`); }