美文网首页
Spring Boot 中使用 GraphQL

Spring Boot 中使用 GraphQL

作者: 清十郎sama | 来源:发表于2019-12-23 17:28 被阅读0次

    了解 GraphQL

    1. 阅读官方文档。官网 https://graphql.org/ 被墙,需要 VPN,可以访问中文站 http://graphql.cn/ .
    2. 了解 GraphQL 在 SpringBoot 框架里的使用:Getting Started with GraphQL and Spring Boot .

    Get Start with GraphQL

    引入 GraphQL(基于 Gradle)

    1. 在主目录下创建 gradle.properties 文件,并在文件中定义 Kotlin 版本
    kotlin.version=1.3.10
    
    1. 添加 GraphQL 依赖
    ext.graphqlJavaKickstartVersion = '5.3.1'
    dependencies {
       implementation("com.graphql-java-kickstart:graphql-spring-boot-starter:${graphqlJavaKickstartVersion}")
       implementation("com.graphql-java-kickstart:graphiql-spring-boot-starter:${graphqlJavaKickstartVersion}")
       implementation("com.graphql-java-kickstart:voyager-spring-boot-starter:${graphqlJavaKickstartVersion}")
       testImplementation("com.graphql-java-kickstart:graphql-spring-boot-starter-test:${graphqlJavaKickstartVersion}")
    }
    

    添加 Schema

    Schema 的写法通常分为两种:

    • coding (比如 Java Code)
    GraphQLObjectType fooType = newObject()
        .name("Foo")
        .field(newFieldDefinition()
                .name("bar")
                .type(GraphQLString))
        .build();
    
    • schema definition language (called SDL)
    type Foo {
        bar: String
    }
    

    如官方推荐一样,强烈建议大家使用 SDL:

    graphql-java offers two different ways of defining the schema: Programmatically as Java code or via a special graphql dsl (called SDL).
    ...
    If you are unsure which option to use we recommend the SDL.

    假设我们要开发一个视频分享网站,那么我们的 Schema 可能是这样的(我们以用户为查询入口):

    type Video {
        id: Int!
        author: String
        title: String
        description: String
        videoAddress: String
        created: String
    }
     
    type User {
        id: Int!
        username: String!
        displayName: String
        birth: String
        created: String
        videos: [Video]
    }
     
    type Query {
        user(
            username: String!
        ): User
    }
    

    这里我们采用 SDL,在 schema 写好后将文件以 *.graphqls 命名放于 classpath:graphql/ 下就会被自动扫描到了。

    By default GraphQL tools uses the location pattern */.graphqls to scan for GraphQL schemas on the classpath. Use the schemaLocationPattern property to customize this pattern.

    如何写 Schema 见:graphql java documentation v11 - schema
    更多 Schema 语法见:graphql schema

    添加 Resolver

    Schema 定义的是查询数据的结构,其真正的逻辑实现则通过 Resolver 来定义。

    Query Resolver

    在定义 Schema 时,我们一定会定义一个名为 Query 的 root schema,这个 root schema 是我们 GraphQL 查询的入口。所以相对应的,我们首先需要定义我们的 QueryResolver:

    @Component
    public class Query implements GraphQLQueryResolver {
        @Autowired
        private UserRepository userRepository;
     
        public User getUser(String username){
            return userRepository.findUserByUsername(username);
        }
    }
    

    因为我们是使用 SpringBoot,记得使用 @Component 注解确保 Resolver 可以被加载。

    More Resolvers

    当然根据不同的场景,我们的的查询结构肯定远不是一个 Query Resolver 能够涵盖的。比如,我们除了作为入口查询的用户信息以外,我们的 Schema 中还定义了通过"User: username" 作为 "Video: author" 来关联查询某个用户发布的所有视频列表。这时,我们就需要更多的 Resolver 来帮我们定义查询逻辑:

    @Component
    public class UserResolver implements GraphQLResolver<User> {
        @Autowired
        private VideoRepository videoRepository;
     
        public List<Video> getVideos(User user) {
            return videoRepository.findVideosByAuthor(user.getUsername());
        }
    }
    

    启动应用服务校验

    1. 浏览器访问 /voyager,查看 GraphQL API
    • http://localhost:8080/voyager
    1. 浏览器访问 /graphiql,进行 GraphQL 查询

    相关文章

      网友评论

          本文标题:Spring Boot 中使用 GraphQL

          本文链接:https://www.haomeiwen.com/subject/cvftoctx.html