I’m trying to make an already incredible lambda micro service I created, that utilizes awsLambdaFastify and GraphQL. So I did a demo on my project last week, and was instantly criticized for even having a fastify server running at all, and made me question the same thing now. So I’ve been trying to find examples of standalone NestJS applications and came across this ServerLess NestJS no HTTP. Ive gotten that working, and Immediately noticed a performance boost (before using fastify and all, my cold starts were around 360 ms, and this standalone app, we are looking at around 20-30 ms).
So with that context, does anyone have experience setting up a standalone NestJS app with no Server Socket running(no fastify, no express, no network) and how would you go about translating the lambda event and context into something I can then feed the standalone app, and how would I do that?
This snippet just shows the index.ts file (copied from the website, tested and working prototype).
I already have resolvers and services set up (GraphQL). I could probably create a custom router to parse the event and then go from there (match it to the correct service etc.) but is there a way that’s maybe built in that can do this for me? Thanks in advanced.
import {
Context,
APIGatewayProxyEvent,
APIGatewayProxyResult,
} from 'aws-lambda';
import { ContextIdFactory } from '@nestjs/core';
import { INestApplicationContext } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { AppService } from './app.service';
import { Logger } from '@nestjs/common';
let app: INestApplicationContext;
/**
* Re-use the application context across function invocations
*/
async function bootstrap(): Promise<INestApplicationContext> {
if (!app) {
app = await NestFactory.createApplicationContext(AppModule, {
// if a custom logger is supposed to be used, disable the default logger here
logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
});
// And in this case attach a custom logger
}
return app;
}
export const handler = async (
event: APIGatewayProxyEvent,
context: Context
): Promise<APIGatewayProxyResult> => {
/**
* Setup the application context
*/
const instance = await bootstrap();
/**
* Instantiate a request-scoped DI sub-tree and obtain the request-scoped top-level injectable
*/
const contextId = ContextIdFactory.create();
console.log(contextId, '<--context id');
instance.registerRequestByContextId({ context }, contextId);
const service = await instance.resolve<AppService>(AppService, contextId);
/**
* Finally, do something with the event we received, this is where I need to route
* to the correct service and pass in the paremeters
*/
const result = service.getHello(event.body);
// Return the computed result
return { statusCode: 200, body: result };
};