Skip to content

Instantly share code, notes, and snippets.

@igor17400
Created November 24, 2022 12:57
Show Gist options
  • Save igor17400/c070c7808f4a61911c08dc2d77f08f4e to your computer and use it in GitHub Desktop.
Save igor17400/c070c7808f4a61911c08dc2d77f08f4e to your computer and use it in GitHub Desktop.
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