gpt4 book ai didi

node.js - AWS Lambda 上的 Nestjs(无服务器框架)|如何访问事件参数?

转载 作者:行者123 更新时间:2023-12-05 03:46:35 27 4
gpt4 key购买 nike

我在 AWS Lambda 上托管一个 Nestjs 应用程序(使用无服务器框架)。请注意,实现在 AWS API Gateway 之后进行。

问题:如何访问 Nest controller 中的 event 参数?

这就是我引导 NestJS 服务器的方式:

import { APIGatewayProxyHandler } from 'aws-lambda';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Server } from 'http';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as awsServerlessExpress from 'aws-serverless-express';
import * as express from 'express';

let cachedServer: Server;

const bootstrapServer = async (): Promise<Server> => {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const app = await NestFactory.create(AppModule, adapter);
app.enableCors();
await app.init();
return awsServerlessExpress.createServer(expressApp);
}

export const handler: APIGatewayProxyHandler = async (event, context) => {
if (!cachedServer) {
cachedServer = await bootstrapServer()
}
return awsServerlessExpress.proxy(cachedServer, event, context, 'PROMISE')
.promise;
};

这是一个 Controller 中的函数:

@Get()
getUsers(event) { // <-- HOW TO ACCESS event HERE?? This event is undefined.
return {
statusCode: 200,
body: "This function works and returns this JSON as expected."
}

我正在努力理解如何访问 event 参数,它可以在“正常” Node 12.x Lambda 函数中轻松访问:

module.exports.hello = async (event) => {
return {
statusCode: 200,
body: 'In a normal Lambda, the event is easily accessible, but in NestJS its (apparently) not.'
};
};

最佳答案

解决方案:

在引导期间将 AwsExpressServerlessMiddleware 添加到您的设置中:

const awsServerlessExpressMiddleware = require('aws-serverless-express/middleware')
app.use(awsServerlessExpressMiddleware.eventContext())

注意:app.use 应该在之前 app.init()

现在可以访问 eventcontext 对象了:

var event = req.apiGateway.event;
var context = req.apiGateway.context;

致谢:This answer on SO

关于node.js - AWS Lambda 上的 Nestjs(无服务器框架)|如何访问事件参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65214210/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com