How do I drain my Fastify GraphQL server on shutdown with Nest.JS?

219 Views Asked by At

I have a Nest.js application with GraphQL and Fastify. If a request is ongoing while the application is shutting down, I am receiving this error:

A GraphQL operation was received during server shutdown. The operation will fail. Consider draining the HTTP server on shutdown; see https://go.apollo.dev/s/drain for details.

I have searched around, but there is no example of draining the HTTP server with Nest.js running Fastify and GraphQL. The best I could come up with is this:

My Apollo config looks something like so:

import { fastifyApolloDrainPlugin } from '@as-integrations/fastify';
import { ApolloDriver, ApolloDriverConfig } from '@nestjs/apollo';
import { HttpAdapterHost } from '@nestjs/core';

static graphqlConfig() {
  return {
    driver: ApolloDriver,
    inject: [
      HttpAdapterHost,
    ],
    useFactory: (
      httpAdapterHost: HttpAdapterHost,
    ) => {
      const fastifyInstance = httpAdapterHost.httpAdapter.getInstance() as any;

      return {
        plugins: [fastifyApolloDrainPlugin(fastifyInstance)],
      } as ApolloDriverConfig;
    },
  };
}

And my main.ts looks something like this:

import { Logger } from '@nestjs/common';
import { NestFactory } from '@nestjs/core';
import { FastifyAdapter, NestFastifyApplication } from '@nestjs/platform-fastify';
import { AppModule } from './app.module';


async function bootstrap() {
  const fastify = new FastifyAdapter();

  const app = await NestFactory.create<NestFastifyApplication>(AppModule, fastify, {
    forceCloseConnections: true,
  });

  // Starts listening for shutdown hooks
  app.enableShutdownHooks();

  await app.listen(3000, '0.0.0.0');
}

bootstrap();

However if I try to cancel the running server with CTRL+C (or using below snippet in main.ts) I still get the same error if a request is ongoing, and that ongoing request is never completed as otherwise expected.

wait(2000).then(async () => {
  console.log('shutting down in 1 second');

  await wait(1000);

  app.close();
});
0

There are 0 best solutions below