【发布时间】:2019-10-25 09:03:49
【问题描述】:
我希望能够从我从请求中收到的 http 请求标头中设置一个上下文变量。这将是一个 jwt 令牌,因此我可以在每个查询中识别我的用户。
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;
}
}
【问题讨论】:
-
你好,你从哪里导入类(或接口?)
GraphQLDataFetchers?我在互联网上找不到任何相关的课程,因为许多图书馆似乎都有它...... -
@maxxyme 是您编写代码的类。只需在任何地方创建并导入它。只需在其上使用 spring 组件装饰器,您就可以开始使用了。类似gist.github.com/cescoferraro/385e2bd40ddbd2c6afda9a7e79d858ad
-
这很奇怪,因为使用 GraphQL Java 工具我不需要编写这样的类,也不需要编写这样的提供程序......
标签: java graphql graphql-java