我可以在 nestjs 的 graphql 查询中访问请求 headers 吗?
Can I access request headers in my graphql query, in nestjs?
我试图在 graphql 的查询中访问用户的 ip-address。但是我无法获得任何 header 信息。如何在我的 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;
}
}
根据此 thread 解析器 context
参数应包含 req
但它取决于 [取决于配置]。
解析器通常采用 (parent, args, context, info)
个参数 - 检查上下文是否在您的参数中定义。
我试图在 graphql 的查询中访问用户的 ip-address。但是我无法获得任何 header 信息。如何在我的 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;
}
}
根据此 thread 解析器 context
参数应包含 req
但它取决于 [取决于配置]。
解析器通常采用 (parent, args, context, info)
个参数 - 检查上下文是否在您的参数中定义。