question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Would it be possible to add sample code for NestJS into https://github.com/vendia/serverless-express/tree/mainline/examples? For example, how to do something like this with v4.0.0?

import { Server } from 'http'
import { NestFactory } from '@nestjs/core'
import { AppModule } from './app.module'
import { Context, APIGatewayEvent } from 'aws-lambda'
import * as ServerlessExpress from '@vendia/serverless-express'
import express from 'express'
import { ExpressAdapter } from '@nestjs/platform-express'

let lambdaProxy : Server

async function bootstrap() {
  const expressServer = express()
  const app = await NestFactory.create(AppModule, new ExpressAdapter(expressServer))
  await app.init()
  return ServerlessExpress.createServer(expressServer)
}

export const handler = (event : APIGatewayEvent, context : Context) => {

  if (!lambdaProxy) {
    bootstrap().then((server) => {
      lambdaProxy = server
      ServerlessExpress.proxy(lambdaProxy, event, context)
    })
  } else {
    ServerlessExpress.proxy(lambdaProxy, event, context)
  }
}

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:4
  • Comments:19 (7 by maintainers)

github_iconTop GitHub Comments

3reactions
jlarmstrongivcommented, Feb 2, 2021

Great idea! My file is similar:

lambda.ts

// transpiling https://github.com/claudiajs/claudia/issues/132
// no relative paths https://github.com/claudiajs/claudia/issues/40#issuecomment-218372727
// timeout https://stackoverflow.com/a/54086731
// aws gateway timeout https://github.com/vendia/serverless-express#considerations
// module.exports https://github.com/janaz/lambda-request-handler/pull/6

import type { Handler, Context } from 'aws-lambda';
import { Server } from 'http';
import { createServer, proxy } from 'aws-serverless-express';
import { eventContext } from 'aws-serverless-express/middleware';

import { NestFactory } from '@nestjs/core';
import {
  ExpressAdapter,
  NestExpressApplication,
} from '@nestjs/platform-express';
import { AppModule } from './app/app.module';
import { useGlobal } from './bootstrap';

// https://github.com/Microsoft/TypeScript/issues/13340
import express = require('express');

// 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

// https://github.com/awslabs/aws-serverless-express/blob/master/examples/basic-starter/lambda.js
const binaryMimeTypes: string[] = [
  'application/javascript',
  'application/json',
  'application/octet-stream',
  'application/xml',
  'font/eot',
  'font/opentype',
  'font/otf',
  'image/gif',
  'image/heic',
  'image/jpeg',
  'image/png',
  'image/svg+xml',
  'image/webp',
  'text/comma-separated-values',
  'text/css',
  'text/html',
  'text/javascript',
  'text/plain',
  'text/text',
  'text/xml',
];

let cachedServer: Server;

// Create the Nest.js server and convert it into an Express.js server
async function bootstrapServer(): Promise<Server> {
  if (!cachedServer) {
    const expressApp = express();
    const nestApp = await NestFactory.create<NestExpressApplication>(
      AppModule,
      new ExpressAdapter(expressApp),
    );
    nestApp.use(eventContext());

    // custom add global pipes, filters, interceptors, etc.
    useGlobal(nestApp);

    await nestApp.init();
    cachedServer = createServer(expressApp, undefined, binaryMimeTypes);
  }
  return cachedServer;
}

// Export the handler : the entry point of the Lambda function
export const handler: Handler = async (event: any, context: Context) => {
  // https://medium.com/safara-engineering/wiring-up-typeorm-with-serverless-5cc29a18824f
  context.callbackWaitsForEmptyEventLoop = false;
  cachedServer = await bootstrapServer();
  return proxy(cachedServer, event, context, 'PROMISE').promise;
};

bootstrap.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app/app.module';
import { NestExpressApplication } from '@nestjs/platform-express';
import helmet from 'helmet';

export async function bootstrap(): Promise<NestExpressApplication> {
  const app = await NestFactory.create<NestExpressApplication>(AppModule);
  return app;
}

export async function useGlobal(
  app: NestExpressApplication,
): Promise<NestExpressApplication> {
  app.use(helmet());
  app.disable('x-powered-by');
  return app;
}

EDIT: I added a helper to an npm package I’m working on. Rough around the edges, but at least I have it written down somewhere 😄

2reactions
michaelmerrillcommented, Feb 4, 2021

Alright, I think I ended up figuring it out. I’ve updated my repo. If I’m off or missing something let me know!

Read more comments on GitHub >

github_iconTop Results From Across the Web

Sample - GitHub
No information is available for this page.
Read more >
First steps | NestJS - A progressive Node.js framework
Nest is a framework for building efficient, scalable Node.js server-side applications. It uses progressive JavaScript, is built with TypeScript and combines ...
Read more >
@nestjs/core examples - CodeSandbox
Learn how to use @nestjs/core by viewing and forking example apps that make use of @nestjs/core on CodeSandbox. ; Latest version9.2.1. License ;...
Read more >
Getting started with continuous integration for Nest.js APIs
Learn how to build RESTful APIs with Nest.js, a Node.js framework ... Our tutorials are platform-agnostic, but use CircleCI as an example.
Read more >
Example | Nestjs-query - Blog
Let's create a simple todo-item graphql example. ... npm i -g @nestjs/clinest new nestjs-query-getting-started. Copy. Install Dependencies#.
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found