MichalLytek / typegraphql-nestjs

TypeGraphQL integration with NestJS
MIT License
144 stars 20 forks source link

@Inject(CONTEXT) is undefined #54

Open ahilke opened 7 months ago

ahilke commented 7 months ago

It seems that @Inject(CONTEXT) is not working with typegraphql-nestjs the way it does for @nestjs/graphql.

I am trying to do something like this:

import { Inject, Injectable } from "@nestjs/common";
import { CONTEXT } from "@nestjs/graphql";
import { Recipe } from "./types";

@Injectable()
export default class RecipeService {
  private readonly recipes: Recipe[] = [];

  constructor(@Inject(CONTEXT) context) {
    console.log('Request Headers:', context?.req?.headers);
  } 
}

With an app module that looks like this:

import { ApolloDriver } from "@nestjs/apollo";
import { Module } from "@nestjs/common";
import { TypeGraphQLModule } from "typegraphql-nestjs";

import RecipeModule from "./recipe/module";

@Module({
  imports: [
    TypeGraphQLModule.forRoot({
      driver: ApolloDriver,
      emitSchemaFile: true,
      context: ({ req, res }) => {
        return { req, res };
      }
    }),
    RecipeModule,
  ],
})
export default class AppModule {}

However, context is just undefined. A similar example using @nestjs/graphql however does work, mostly following https://docs.nestjs.com/fundamentals/injection-scopes#request-provider.

I have not found anything in the docs that says this should not work or how to achieve this differently, so if this is expected or just works differently please let me know. I think this may be a similar issue as discussed in https://github.com/MichalLytek/typegraphql-nestjs/issues/22, but it was never reproduced or fixed.

Initially I was not sure myself where the issue comes from, so I have created a reproduction with both typegraphql-nestjs and @nestjs/graphql here: https://github.com/ahilke/typegraphql-nestjs-inject-context.

Thank you for your support!

MichalLytek commented 7 months ago

I think you need to use @Ctx() decorator from TypeGraphQL to inject context into resolver method. You can't inject context into constructor.

ahilke commented 7 months ago

Thanks for the quick reply!

Yeah, @Ctx() does work in resolvers. Maybe my example wasn't the best, because I am trying to access the Request/Context not within a resolver itself, but just generally within a Nest provider.

In my application, I have a service that must be a singleton per request that is then shared between all resolvers as well as some middlewares via Nest's dependency injection. Within that singleton, I need access to the request headers, thus I tried to inject the context there. As mentioned, following the examples from @nestjs/grapqhl this works quite well, but I haven't been able to make something like this work for typegraphql-nestjs. I could probably somehow work around this, but I think ideally it would work through Nest's dependency system.