Skip to content

Instantly share code, notes, and snippets.

@hideokamoto
Created February 27, 2020 16:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hideokamoto/b15ea848941405abb3c97a62e43dc88b to your computer and use it in GitHub Desktop.
Save hideokamoto/b15ea848941405abb3c97a62e43dc88b to your computer and use it in GitHub Desktop.
import { NestApplicationOptions, INestApplication } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { Server } from 'http';
import { ExpressAdapter } from '@nestjs/platform-express';
import * as serverless from 'aws-serverless-express';
import * as express from 'express';
import { APIGatewayProxyEvent, Context, APIGatewayEvent } from 'aws-lambda';
let cachedServer: Server;
export type NestAplicationCallback = (
app: INestApplication,
) => INestApplication | Promise<INestApplication>;
const defaultCallback: NestAplicationCallback = app => app;
export class ServerlessNestjsApplicationFactory<T = any> {
private readonly AppModule: T;
private options: NestApplicationOptions;
private callback: NestAplicationCallback;
constructor(
AppModule: T,
options: NestApplicationOptions = {},
callback: NestAplicationCallback = defaultCallback,
) {
this.AppModule = AppModule;
this.options = options;
this.callback = callback;
}
public updateOptions(options: NestApplicationOptions) {
this.options = options;
return this;
}
public updateCallback(callback: NestAplicationCallback) {
this.callback = callback;
return this;
}
public async createApplication() {
const expressApp = express();
const adapter = new ExpressAdapter(expressApp);
const application = await NestFactory.create(
this.AppModule,
adapter,
this.options,
);
const app = await this.callback(application);
app.init();
return serverless.createServer(expressApp);
}
public async run(
event: APIGatewayProxyEvent | APIGatewayEvent,
context: Context,
) {
if (!cachedServer) {
cachedServer = await this.createApplication();
}
const result = await serverless.proxy(
cachedServer,
event,
context,
'PROMISE',
).promise;
return result;
}
}
import { APIGatewayProxyHandler } from 'aws-lambda';
import { AppModule } from './app.module';
import { ServerlessNestjsApplicationFactory } from './nestjs-serverless';
export const handler: APIGatewayProxyHandler = async (event, context) => {
const app = new ServerlessNestjsApplicationFactory<AppModule>(
AppModule,
{},
app => {
app.enableCors();
return app;
},
);
const result = await app.run(event, context);
return result;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment