Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

updates readme for nestjs #142

Open
wants to merge 1 commit into
base: master
Choose a base branch
from

Conversation

Jwagner347
Copy link

This PR updates the Readme with instructions on running with NestJS and with NestJS/GraphQL. This should also close out #115.

Checklist

@Jwagner347 Jwagner347 mentioned this pull request Dec 16, 2022
2 tasks
@adrai
Copy link
Member

adrai commented Dec 16, 2022

IMO, this is all knowledge not specific to aws-lambda-fastify, but general to how AWS Lambda works in combination with NestJS...
Isn't this making the Readme more noisy?

@Jwagner347
Copy link
Author

I would say it's about how aws-lambda-fastify works in combination with NestJS, not just generic AWS Lambda. But, I do see your point; however, there is an open issue inquiring about this which led to some more discussion and someone asked me to update the readme in order to persist the knowledge. Maybe that's not the right place for it, though.

@mcollina
Copy link
Member

I think a better place for this documentation is on the Nest.js website.
We do not have the resources to support Nest.js users while they do.
i would not block this but I would not LGTM it either.

@mcollina mcollina requested a review from adrai December 16, 2022 22:01
@adrai
Copy link
Member

adrai commented Dec 16, 2022

I think a better place for this documentation is on the Nest.js website.

We do not have the resources to support Nest.js users while they do.

i would not block this but I would not LGTM it either.

That's exactly what I meant 😉

@Jwagner347
Copy link
Author

@mcollina I agree. I'll see about getting this added to their documentation.

@adrai adrai added the documentation Improvements or additions to documentation label Dec 16, 2022
@adrai
Copy link
Member

adrai commented Dec 18, 2022

@Uzlopak ok for you if we close this PR in favor to document it on the Nest.js side somewhere?

@adrai adrai removed their request for review December 18, 2022 10:49
@Uzlopak
Copy link
Contributor

Uzlopak commented Dec 18, 2022

I am totally ok with it as long it is somewhere documented?!

Is it likely that nest js will accept that additional documentation?

@toptal-dave
Copy link

Just want to say that I was looking around today and was very happy to find a PR here with documentation about using Next.js with Fastify on Lambda. Is there a PR for Nest.js documentation I can upvote or whatever? I really appreciate being able to find some documentation somewhere on this so I hope it gets out there on the web somewhere somehow...

@toptal-dave
Copy link

@Jwagner347 I see some issues with the code in the README. Mostly variable names and types not lining up because the code is combined. Here's how it should look:

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import awsLambdaFastify, { PromiseHandler } from '@fastify/aws-lambda';
import fastify, { FastifyInstance, FastifyServerOptions } from 'fastify';
import { Context, APIGatewayProxyEvent } from 'aws-lambda';
import { Logger } from '@nestjs/common';

interface NestApp {
  app: NestFastifyApplication;
  instance: FastifyInstance;
}

let cachedNestApp;

async function bootstrap(): Promise<NestApp> {
  const serverOptions: FastifyServerOptions = {
    logger: (process.env.LOGGER || '0') == '1',
  };
  const instance: FastifyInstance = fastify(serverOptions);
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    new FastifyAdapter(instance),
    {
      logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
    },
  );

  const CORS_OPTIONS = {
    origin: '*',
    allowedHeaders: '*',
    exposedHeaders: '*',
    credentials: false,
    methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
  };

  app.register(require('fastify-cors'), CORS_OPTIONS);

  app.setGlobalPrefix(process.env.API_PREFIX);

  await app.init();

  return {
    app,
    instance,
  };
}

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context,
): Promise<PromiseHandler> => {
  if (!cachedNestApp) {
    const nestApp: NestApp = await bootstrap();
    cachedNestApp = awsLambdaFastify(nestApp.instance, {
      decorateRequest: true,
    });
  }

  return cachedNestApp(event, context);
};

However, we have a bigger issue and that is a type mismatch when adapting Fastify:

Argument of type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>' is not assignable to parameter of type 'FastifyHttp2Options<any, FastifyBaseLogger> | FastifyHttp2SecureOptions<any, FastifyBaseLogger> | FastifyHttpsOptions<...> | FastifyInstance<...> | FastifyServerOptions<...>'.
  Type 'FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, FastifyTypeProviderDefault>' is not assignable to type 'FastifyInstance<any, any, any, FastifyBaseLogger, FastifyTypeProviderDefault>'.
    The types of 'withTypeProvider().decorate' are incompatible between these types.
      Type 'DecorationMethod<FastifyInstance<RawServerDefault, IncomingMessage, ServerResponse<IncomingMessage>, FastifyBaseLogger, Provider>, FastifyInstance<...>>' is not assignable to type 'DecorationMethod<FastifyInstance<any, any, any, FastifyBaseLogger, Provider>, FastifyInstance<any, any, any, FastifyBaseLogger, Provider>>'.
        Target signature provides too few arguments. Expected 2 or more, but got 1.

I'll see if I can figure it out and update below.

@toptal-dave
Copy link

I submitted an bug report issue here.

@toptal-dave
Copy link

OK I took another crack at fixing it using the Fastify instance from the NestFactory; plus I updated some of the parts to work with the latest Nest version 10.2:

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import awsLambdaFastify, { PromiseHandler } from '@fastify/aws-lambda';
import { Context, APIGatewayProxyEvent } from 'aws-lambda';
import { Logger } from '@nestjs/common';

let cachedNestApp;

async function bootstrap(): Promise<NestFastifyApplication> {
  // Create the app
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    // Use an env var to set the logger to nest or console
    new FastifyAdapter({ logger: (process.env.LOGGER || '0') == '1' }),
    {
      logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
    },
  );

  // Enable cors
  app.enableCors({
    origin: '*',
    allowedHeaders: '*',
    exposedHeaders: '*',
    credentials: false,
    methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
  });

  // Set the prefix as necessary
  app.setGlobalPrefix(process.env.API_PREFIX);

  await app.init();

  return app;
}

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context,
): Promise<PromiseHandler> => {
  // If there's no cached app
  if (!cachedNestApp) {
    // Bootstrap
    const nestApp: NestFastifyApplication = await bootstrap();
    // Create an AWS Lambda Fastify cached app from the Nest app
    cachedNestApp = awsLambdaFastify(nestApp.getHttpAdapter().getHttpServer(), {
      decorateRequest: true,
    });
  }

  return cachedNestApp(event, context);
};

@toptal-dave
Copy link

I got it working!

The code that works is as follows:

import { NestFactory } from '@nestjs/core';
import {
  FastifyAdapter,
  NestFastifyApplication,
} from '@nestjs/platform-fastify';
import { AppModule } from './app.module';
import awsLambdaFastify, { PromiseHandler } from '@fastify/aws-lambda';
import { Context, APIGatewayProxyEvent } from 'aws-lambda';
import { Logger } from '@nestjs/common';
import { fastify, FastifyServerOptions, FastifyInstance } from 'fastify';

interface NestApp {
  app: NestFastifyApplication;
  instance: FastifyInstance;
}

let cachedNestApp;

async function bootstrap(): Promise<NestApp> {
  const serverOptions: FastifyServerOptions = {
    logger: (process.env.LOGGER || '0') == '1',
  };
  const instance: FastifyInstance = fastify(serverOptions);
  // Create the app
  const app = await NestFactory.create<NestFastifyApplication>(
    AppModule,
    // Use an env var to set the logger to nest or console
    new FastifyAdapter(instance),
    {
      logger: !process.env.AWS_EXECUTION_ENV ? new Logger() : console,
    },
  );

  // Enable cors
  app.enableCors({
    origin: '*',
    allowedHeaders: '*',
    exposedHeaders: '*',
    credentials: false,
    methods: ['GET', 'PUT', 'OPTIONS', 'POST', 'DELETE'],
  });

  // Set the prefix as necessary
  app.setGlobalPrefix(process.env.API_PREFIX);

  await app.init();

  return {
    app,
    instance,
  };
}

export const handler = async (
  event: APIGatewayProxyEvent,
  context: Context,
): Promise<PromiseHandler> => {
  // If there's no cached app
  if (!cachedNestApp) {
    // Bootstrap
    const nestApp: NestApp = await bootstrap();
    // Create an AWS Lambda Fastify cached app from the Nest app
    cachedNestApp = awsLambdaFastify(nestApp.instance, {
      decorateRequest: true,
    });
  }

  return cachedNestApp(event, context);
};

I had to make sure that the Fastify version was the same between what was installed here and what @nestjs/platform-fastify as per this comment.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
documentation Improvements or additions to documentation
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants