graphqlip-addressnestjs

Can I access request headers in my graphql query, in nestjs?


I am trying to access the ip-address of the user in the query of graphql. But I cannot reach any header information. How can I access the context I am creating in my factory, inside of my graphql requests?

// app.module.ts
...

@Module({
  imports: [
    ConfigModule,
    GraphQLModule.forRootAsync({
      imports: [ 
        LanguageModule,
        SearchModule],
      inject: [ConfigService],
      useFactory: () => ({
        autoSchemaFile: 'schema.gql',
        debug: true,
        fieldResolverEnhancers: ['guards'],
        formatError: (error: GraphQLError): GraphQLFormattedError => {
          return error.originalError instanceof BaseException
            ? error.originalError.serialize()
            : error;
        },
        context: ({ req }): object => {
          console.log("req.ip: ", req.ip); // Here I have the ip
          return { req };
        },
      }),
    }), 
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}

// search.resolver.ts
...

@Resolver(() => Search)
export class SearchResolver {
  constructor(private readonly service: service) {}

  @Query(() => Search)
  async search(@Args() args: SearchArgs): Promise<Search> {

    // I want the ip here, I want to send it as an argument into the query function below
    const response = await this.service.query(args.query, {
      language: args.language,
    });
    return response;
  }
}

Solution

  • According to this thread resolver context parameter should contain req but it depends [on configuration].

    Resolvers typically takes (parent, args, context, info) arguments - check if context is defined in yours.