nestjs / graphql

GraphQL (TypeScript) module for Nest framework (node.js) 🍷
https://docs.nestjs.com/graphql/quick-start
MIT License
1.46k stars 397 forks source link

Unable to Specify forRoutes Argument When Assigning Middleware to '/graphql' Endpoint #3180

Open stringthread opened 8 months ago

stringthread commented 8 months ago

Is there an existing issue for this?

Current behavior

Using app.setGlobalPrefix and GraphQLModule.forRoot, I cannot specify /graphql endpoint in the argument of consumer.apply(middleware).forRoutes.

// main.ts
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('prefix');
  await app.listen(3000);
}
bootstrap();
// app.module.ts
import { Module, NestModule, MiddlewareConsumer } from '@nestjs/common';
import { GraphQLModule } from '@nestjs/graphql';
import { ApolloDriver } from '@nestjs/apollo';
import { AppResolver } from './app.resolver'; // Simple sample resolver
import * as path from 'path';

@Module({
  imports: [
    GraphQLModule.forRoot({
      driver: ApolloDriver,
      autoSchemaFile: path.join(process.cwd(), 'src/schema.gql'),
    }),
  ],
  providers: [AppResolver],
})
export class AppModule implements NestModule {
  configure(consumer: MiddlewareConsumer) {
    consumer
      .apply((req, res, next) => {
        console.log('apply');
        next();
      })
      .forRoutes('graphql'); // This don't work
  }
}

Minimum reproduction code

https://codesandbox.io/p/devbox/nestjs-graphql-middleware-issue-8d6qfr

Steps to reproduce

  1. npm start:dev
  2. access /graphql endpoint
  3. See terminal outputs

Expected behavior

The middleware should be called when I access /graphql endpoint. In my minimum example, apply should be shown in terminal outputs.

Package version

12.1.1

Graphql version

graphql: 16.8.1 @apollo/server: 4.10.1 @nestjs/apollo: 12.1.0

NestJS version

10.3.3

Node.js version

20.11.0

In which operating systems have you tested?

Other

I have found a workaround to avoid this bug: consumer.apply(middleware).forRoutes worked properly when I specified exclude option in app.setGlobalPrefix and add "graphql".

// main.ts
async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.setGlobalPrefix('prefix', {
    // works properly with the following option
    exclude: ['graphql']
  });
  await app.listen(3000);
}

(I have also noticed it in my minimal repro as a comment.)

kamilmysliwiec commented 3 days ago

Would you like to create a PR for this issue?