我希望能够从从请求收到的 http 请求 header 中设置上下文变量。这将是一个 jwt token ,因此我可以在每次查询时识别我的用户。
package br.com.b2breservas.api;
import com.google.common.base.Charsets;
import com.google.common.io.Resources;
import graphql.GraphQL;
import graphql.schema.GraphQLSchema;
import graphql.schema.idl.RuntimeWiring;
import graphql.schema.idl.SchemaGenerator;
import graphql.schema.idl.SchemaParser;
import graphql.schema.idl.TypeDefinitionRegistry;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.io.IOException;
import java.net.URL;
import static graphql.schema.idl.TypeRuntimeWiring.newTypeWiring;
@Component
public class GraphQLProvider {
@Autowired
GraphQLDataFetchers graphQLDataFetchers;
private GraphQL graphQL;
@PostConstruct
public void init() throws IOException {
URL url = Resources.getResource("schema.graphqls");
String sdl = Resources.toString(url, Charsets.UTF_8);
GraphQLSchema graphQLSchema = buildSchema(sdl);
this.graphQL = GraphQL.newGraphQL(graphQLSchema).build();
}
private GraphQLSchema buildSchema(String sdl) {
TypeDefinitionRegistry typeRegistry = new SchemaParser().parse(sdl);
RuntimeWiring runtimeWiring = buildWiring();
SchemaGenerator schemaGenerator = new SchemaGenerator();
return schemaGenerator.makeExecutableSchema(typeRegistry, runtimeWiring);
}
private RuntimeWiring buildWiring() {
return RuntimeWiring.newRuntimeWiring()
.type(newTypeWiring("Query")
.dataFetcher("books", graphQLDataFetchers.getBooks()))
.type(newTypeWiring("Query")
.dataFetcher("bookById", graphQLDataFetchers.getBookByIdDataFetcher()))
.type(newTypeWiring("Book")
.dataFetcher("author", graphQLDataFetchers.getAuthorDataFetcher()))
.build();
}
@Bean
public GraphQL graphQL() {
return graphQL;
}
}
最佳答案
您可以创建一个内部包含 JWT 或仅包含 HttpServletRequest
的自定义对象:
public class GraphQLContext {
private HttpServletRequest httpServletRequest;
}
执行 GraphQL
查询时,您创建此上下文对象并将其设置为 ExecutionInput
。大多数Web框架应该提供一些方法来轻松访问当前的HttpServletRequest
:
GraphQLContext context = new GraphQLContext(httpServletRequest);
ExecutionInput executionInput = ExecutionInput.newExecutionInput()
.query(query)
.context(context)
.build();
ExecutionResult result = graphQL.execute(executionInput);
然后在数据 getter 中,可以通过以下方式获取上下文:
@Override
public Object get(DataFetchingEnvironment env) throws Exception {
GraphQLContext context = env.getContext();
HttpServletRequest httpServletRequest = context.getHttpServletRequest();
}
关于java - 如何使用 graphql-java 从请求 header 设置上下文,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56535259/