【问题标题】:Can I access request headers in my graphql query, in nestjs?我可以在我的 graphql 查询中访问请求标头,在 nestjs 中吗?
【发布时间】:2020-06-23 05:42:54
【问题描述】:

我正在尝试在 graphql 的查询中访问用户的 IP 地址。但我无法获得任何标题信息。如何在我的 graphql 请求中访问我在工厂中创建的上下文?

// 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;
  }
}

【问题讨论】:

    标签: graphql ip-address nestjs


    【解决方案1】:

    根据这个thread解析器context参数应该包含req,但这取决于[取决于配置]。

    解析器通常采用 (parent, args, context, info) 参数 - 检查您的上下文中是否定义了上下文。

    【讨论】:

    • 谢谢!我可以像你说的那样使用 context 参数访问它。像这样:'''@Query(() => Search) async search(@Args() args: SearchArgs, @Context() context): Promise { console.log(context); ... }'''
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-12-18
    • 2021-04-20
    • 2022-09-26
    • 1970-01-01
    • 2021-10-31
    • 2020-12-14
    • 2021-04-08
    相关资源
    最近更新 更多