简体   繁体   English

如何在无服务器离线中使用 Cognito 事件/触发器调用 lambda 以进行本地测试

[英]How to invoke lambda with Cognito event/trigger in serverless-offline for local test

I'm trying to write a trio of Cognito AuthChallenge lambdas for custom auth flow.我正在尝试为自定义身份验证流程编写三个 Cognito AuthChallenge lambda。 I wanted to use serverless-offline to develop and test the lambdas locally with nodejs (also in jest tests in cicd pipeline).我想使用 serverless-offline 在本地使用 nodejs 开发和测试 lambdas(也在 cicd 管道中的开玩笑测试中)。

For example, here is a simplified handler code with VerifyAuthChallengeResponseTriggerEvent type from aws-lambda package:例如,下面是 aws-lambda 包中带有VerifyAuthChallengeResponseTriggerEvent类型的简化处理程序代码:

import {
    VerifyAuthChallengeResponseTriggerEvent,
    VerifyAuthChallengeResponseTriggerHandler
} from "aws-lambda/trigger/cognito-user-pool-trigger/verify-auth-challenge-response";

export const verifyChallengeHandler: VerifyAuthChallengeResponseTriggerHandler =
    async (event: VerifyAuthChallengeResponseTriggerEvent):
        Promise<VerifyAuthChallengeResponseTriggerEvent> => {

        event.response.answerCorrect = event.request.privateChallengeParameters["code"] == event.request.challengeAnswer;

        return event;
    };

I found everywhere only examples of using API Gateway with http event, so when I tried it locally with following config under the functions in serverless config, it also worked:我到处都发现只有使用带有 http 事件的 API 网关的示例,所以当我在无服务器配置中的functions下使用以下配置在本地尝试它时,它也有效:

events: [
    {
        http: {
            method: "post",
            path: "auth-verify",
            cors: {
                origin: '*',
                headers:[
                    "Content-Type",
                    "X-Amz-Date",
                    "X-Amz-Security-Token",
                    "Authorization",
                    "X-Api-Key",
                    "X-Requested-With",
                    "Accept",
                ],
                allowCredentials: true,
            },
        },
    },
],

However, I'd have to rewrite the handler code, so that it works with different event type.但是,我必须重写处理程序代码,以便它适用于不同的事件类型。 That is not great as it would be different code for testing from the code to be deployed.这不是很好,因为用于测试的代码与要部署的代码不同。

import { ValidatedEventAPIGatewayProxyEvent } from '@libs/apiGateway';
import { middyfy } from '@libs/lambda';
import schema from './schema';


const verifyChallengeHandler: ValidatedEventAPIGatewayProxyEvent<typeof schema> = async(event) => {
   ... 

Is there a way to configure serverless and what command to call that I can invoke the lambdas locally and also in jest tests with correct events and without changing the code?有没有办法配置无服务器以及调用什么命令,我可以在本地调用 lambda,也可以在具有正确事件且不更改代码的开玩笑测试中调用? I'm also fine with creating a custom mock of events (but how to specify them?).我也可以创建自定义的事件模拟(但如何指定它们?)。 Ie. IE。 to use config under functions as something like this:functions下使用配置,如下所示:

events: [
    {
        cognitoUserPool: {
            pool: <some_pool_name>,
            trigger: 'VerifyAuthChallengeResponse' as const,
            existing: false,
        },
    },

Well, seems like I found the answer, which wasn't finally that difficult, but just to complete this question, I'll post it here.好吧,似乎我找到了答案,这最终并不难,但只是为了完成这个问题,我会在这里发布。 It's based on this answer aws lambda: invoke with payload from cli where I start local lambda code with:它基于这个答案aws lambda: invoke with payload from cli ,我在其中启动本地 lambda 代码:

npm start

and then invoke lambda with mock-event.json file data as event in CLI like this:然后在 CLI 中使用 mock-event.json 文件数据作为事件调用 lambda,如下所示:

aws lambda invoke /dev/null \
  --endpoint-url http://localhost:3002 \
  --function-name lambda-handler-dev-lambdaHandler \
  --invocation-type Event \
  --payload file:///home/...<path to my project>/src/functions/lambda-handler/mock-event.json

This was pretty nice, as one terminal waits for changes and reloads them after any code change and it also shows the log output of the lambda, while I use the other terminal just to invoke lambda.这非常好,因为一个终端等待更改并在任何代码更改后重新加载它们,它还显示 lambda 的日志输出,而我使用另一个终端只是调用 lambda。 I like the clarity and speed of the flow.我喜欢流动的清晰度和速度。

I found also other way from Serverless (in the README file of my serverless project template, I was blind not to see it before, yeah?), and that executed everything in one terminal (logs and responses in one), but it took a bit of time to spin up and invoke the lambda.我还从 Serverless 中找到了其他方式(在我的无服务器项目模板的 README 文件中,我之前看不到它,是吗?),并且在一个终端中执行所有内容(日志和响应在一个终端中),但它需要一个需要一点时间来启动并调用 lambda。 On the other side, unlike from the aws lambda cli which gave me only some basic response back, it also printed nice and complete response object.另一方面,与只给我一些基本响应的 aws lambda cli 不同,它还打印了漂亮而完整的响应对象。 It can be invoked as:它可以被调用为:

npx sls invoke local -f lambda-handler-dev-lambdaHandler --path src/functions/lambda-handler/mock-event.json

That's so far for a local development.到目前为止,对于本地开发而言。 Regarding the testing, I'm creating the usual jest test in __tests__ folder where you create mock objects and call the handler method:关于测试,我在__tests__文件夹中创建通常的笑话测试,您可以在其中创建模拟对象并调用处理程序方法:

const event = {foo: bar};
const main = require("../src/functions/lambda-handler/handler").main;
const response = await main(...event-params...);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在 function 之前在 mocha 测试中启动 serverless-offline - How to start serverless-offline in mocha test before function 如何在无服务器离线状态下从另一个 lambda 调用 lambda function? - How to invoke a lambda function from another lambda in serverless offline? 在本地 docker localhost:8000 中使用 dynamodb 和在 localhost:4500 上运行的 serverless-framework serverless-offline 应用程序 - Using dynamodb in local docker localhost:8000 with serverless-framework serverless-offline application running on localhost:4500 无服务器离线 - API REST 节点 typescript - Serverless-offline - API REST node typescript serverless-offline 可选路径参数 - serverless-offline optional path parameter 带有无服务器离线阶段中断路由的 aws-serverless-express - aws-serverless-express with serverless-offline stage breaks routing 如何使用无服务器离线将 lambda 的离线跟踪发送到本地 xray 守护程序? - How to send lambda's offline traces to a local xray daemon with serverless offline? 如何摆脱包装无服务器离线 html 响应正文的双引号? - How to get rid of double quotes wrapping serverless-offline html response body? 无法获取路径:/{proxy+} 工作(无服务器离线) - Cant get path: /{proxy+} to work (serverless-offline) AWS Lambda function 不会从 Cognito PostConfirmation 事件触发,但它在测试中有效 - AWS Lambda function doesn't trigger from Cognito PostConfirmation event, but it works in Test
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM