Created
March 5, 2019 11:26
-
-
Save csakbalint/7fe406bd1b15124180a988c87d57cf9b to your computer and use it in GitHub Desktop.
nestjs-serverless-swagger
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 'reflect-metadata'; | |
import { Handler, Context } from 'aws-lambda'; | |
import { createServer, proxy } from 'aws-serverless-express'; | |
import { eventContext } from 'aws-serverless-express/middleware'; | |
import * as express from 'express'; | |
import { Server } from 'http'; | |
import { SwaggerModule, DocumentBuilder } from '@nestjs/swagger'; | |
import { INestApplication, INestExpressApplication } from '@nestjs/common'; | |
import { NestFactory } from '@nestjs/core'; | |
import { AppModule } from './app.module'; | |
// NOTE: If you get ERR_CONTENT_DECODING_FAILED in your browser, this is likely | |
// due to a compressed response (e.g. gzip) which has not been handled correctly | |
// by aws-serverless-express and/or API Gateway. Add the necessary MIME types to | |
// binaryMimeTypes below | |
const binaryMimeTypes: string[] = []; | |
let cachedServer: Server; | |
process.on('unhandledRejection', console.error); | |
process.on('uncaughtException', console.error); | |
async function setupSwagger(app: INestApplication & INestExpressApplication) { | |
const options = new DocumentBuilder() | |
.setTitle('Cats example') | |
.setDescription('The cats API description') | |
.setVersion('1.0') | |
.addTag('cats') | |
.build(); | |
const document = SwaggerModule.createDocument(app, options); | |
SwaggerModule.setup('swagger', app, document); | |
} | |
async function bootstrap(): Promise<Server> { | |
if (!cachedServer) { | |
try { | |
const expressApp = express(); | |
const nestApp = await NestFactory.create(AppModule, expressApp); | |
nestApp.use(eventContext()); | |
nestApp.enableCors(); | |
await nestApp.init(); | |
setupSwagger(nestApp); | |
cachedServer = createServer(expressApp, undefined, binaryMimeTypes); | |
} catch (error) { | |
return Promise.reject(error); | |
} | |
} | |
return Promise.resolve(cachedServer); | |
} | |
export const handler: Handler = async (event: any, context: Context) => | |
proxy(await bootstrap(), event, context, 'PROMISE').promise; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment