簡體   English   中英

AWS Lambda(無服務器框架)上的 Nestjs | 如何訪問事件參數?

[英]Nestjs on AWS Lambda (Serverless Framework) | How to access the event parameter?

我在 AWS Lambda 上托管 Nestjs 應用程序(使用無服務器框架)。 請注意,實施在 AWS API 網關之后。

問:如何訪問我的 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 中的 function:

@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參數,它可以在“普通”節點 12.x Lambda function 中輕松訪問:

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 object:

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

學分: 這個答案

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM