-
-
Save igor17400/c070c7808f4a61911c08dc2d77f08f4e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { NestFactory } from '@nestjs/core'; | |
import { | |
FastifyAdapter, | |
NestFastifyApplication, | |
} from '@nestjs/platform-fastify'; | |
import { AppModule } from './app/app.module'; | |
import { FastifyServerOptions, FastifyInstance, fastify } from 'fastify'; | |
import * as awsLambdaFastify from 'aws-lambda-fastify'; | |
import { | |
Context, | |
APIGatewayProxyEvent, | |
APIGatewayProxyResult, | |
} from 'aws-lambda'; | |
import { Logger } from '@nestjs/common'; | |
interface NestApp { | |
app: NestFastifyApplication; | |
instance: FastifyInstance; | |
} | |
let cachedNestApp: NestApp; | |
async function bootstrapServer(): Promise<NestApp> { | |
const serverOptions: FastifyServerOptions = { | |
logger: true, | |
}; | |
const instance: FastifyInstance = fastify(serverOptions); | |
const app = await NestFactory.create<NestFastifyApplication>( | |
AppModule, | |
new FastifyAdapter(instance), | |
{ | |
logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console, | |
} | |
); | |
app.setGlobalPrefix(process.env.API_PREFIX); | |
await app.init(); | |
return { | |
app, | |
instance, | |
}; | |
} | |
export const handler = async ( | |
event: APIGatewayProxyEvent, | |
context: Context | |
): Promise<APIGatewayProxyResult> => { | |
if (!cachedNestApp) { | |
cachedNestApp = await bootstrapServer(); | |
} | |
const proxy = awsLambdaFastify(cachedNestApp.instance); | |
return proxy(event, context); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment