This work is licensed under a Creative Commons Attribution-NonCommercial 4.0 International License.
GraphQL-Java(零)从SpringBoot服务端开始
引入依赖
1
2
3
4
5
6
7
dependencies{implementation'com.graphql-java:graphql-java:14.1'// NEW
implementation'com.graphql-java:graphql-java-spring-boot-starter-webmvc:1.0'// NEW
implementation'com.google.guava:guava:26.0-jre'// NEW
implementation'org.springframework.boot:spring-boot-starter-web'testImplementation'org.springframework.boot:spring-boot-starter-test'}
定义Schema
在src/main/resources中创建schema.graphqls如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
@ComponentpublicclassGraphQLProvider{privateGraphQLgraphQL;@BeanpublicGraphQLgraphQL(){returngraphQL;}/**
* 用Guava Resources读取资源文件
*
* @throws IOException
*/@PostConstructpublicvoidinit()throwsIOException{URLurl=Resources.getResource("schema.graphqls");Stringsdl=Resources.toString(url,Charsets.UTF_8);GraphQLSchemagraphQLSchema=buildSchema(sdl);this.graphQL=GraphQL.newGraphQL(graphQLSchema).build();}privateGraphQLSchemabuildSchema(Stringsdl){// TODO: we will create the schema here later
}}
我们通过google的Guava Resources来读取Schema.graphql文件,并且通过@Bean注解把GraphQL实例暴露出去,GraphQL Java Spring adapter会使用这个GraphQL实例来把schema匹配到`/graphql’路径,以后通过这个路径调用所有接口。
@ComponentpublicclassGraphQLDataFetchers{privatestaticList<Map<String,String>>books=Arrays.asList(ImmutableMap.of("id","book-1","name","Harry Potter and the Philosopher's Stone","pageCount","223","authorId","author-1"),ImmutableMap.of("id","book-2","name","Moby Dick","pageCount","635","authorId","author-2"),ImmutableMap.of("id","book-3","name","Interview with the vampire","pageCount","371","authorId","author-3"));privatestaticList<Map<String,String>>authors=Arrays.asList(ImmutableMap.of("id","author-1","firstName","Joanne","lastName","Rowling"),ImmutableMap.of("id","author-2","firstName","Herman","lastName","Melville"),ImmutableMap.of("id","author-3","firstName","Anne","lastName","Rice"));publicDataFetchergetBookByIdDataFetcher(){returndataFetchingEnvironment->{StringbookId=dataFetchingEnvironment.getArgument("id");returnbooks.stream().filter(book->book.get("id").equals(bookId)).findFirst().orElse(null);};}publicDataFetchergetAuthorDataFetcher(){returndataFetchingEnvironment->{Map<String,String>book=dataFetchingEnvironment.getSource();StringauthorId=book.get("authorId");returnauthors.stream().filter(author->author.get("id").equals(authorId)).findFirst().orElse(null);};}}