【发布时间】:2022-07-13 17:52:11
【问题描述】:
我正在尝试设置 NestJS 无服务器应用程序。该应用程序以sls offline start 开始正常运行。但问题是应用程序不断地重新启动自己。未设置缓存服务器。每次我调用端点时,服务器都会重新启动。
Lambda
import { Handler, Context } from 'aws-lambda';
import { Server } from 'http';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';
import { NestFactory } from '@nestjs/core';
import { ExpressAdapter } from '@nestjs/platform-express';
import { AppModule } from './app.module';
import express from "express";
let cachedServer: Server;
async function bootstrapServer(): Promise<Server> {
console.log("cached?", !!cachedServer);
if (!cachedServer) {
const expressApp = express();
const nestApp = await NestFactory.create(AppModule, new ExpressAdapter(expressApp))
nestApp.use(eventContext());
await nestApp.init();
// here is the set
cachedServer = createServer(expressApp);
}
return cachedServer;
}
export const handler: Handler = async (event: any, context: Context) => {
// here is another set
cachedServer = await bootstrapServer();
return proxy(cachedServer, event, context, 'PROMISE').promise;
}
输出
ANY /dev (λ: graphql)
cached? false
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [NestFactory] Starting Nest application... +186ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [InstanceLoader] AppModule dependencies initialized +3ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [RoutesResolver] AppController {/}: +0ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [RouterExplorer] Mapped {/, GET} route +1ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [NestApplication] Nest application successfully started +0ms
(λ: graphql) RequestId: cl3r0i9bu000b49v67zkk50gl Duration: 12.56 ms Billed Duration: 13 ms
ANY /dev (λ: graphql)
cached? false
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [NestFactory] Starting Nest application... +188ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [InstanceLoader] AppModule dependencies initialized +3ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [RoutesResolver] AppController {/}: +1ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [RouterExplorer] Mapped {/, GET} route +0ms
[Nest] 24777 - 05/29/2022, 9:00:31 AM LOG [NestApplication] Nest application successfully started +0ms
(λ: graphql) RequestId: cl3r0i9h5000e49v65mfs21vo Duration: 15.21 ms Billed Duration: 16 ms
有人有什么想法吗?
【问题讨论】:
标签: nestjs serverless serverless-framework