热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

GraphQLSpringBoot使用

GraphQL Spring Boot 使用

项目地址 https://github.com/helloworlde/spring-boot-graphql-demo

使用 SpringBoot 和 GraphQL 创建一个最简单的增删改查接口应用,使用 MongoDB 存储数据

创建应用

  • 添加依赖
dependencies {
    implementation('org.springframework.boot:spring-boot-starter-web')
    implementation('org.springframework.boot:spring-boot-starter-data-mongodb')

    compileOnly('org.projectlombok:lombok')
    testImplementation('org.springframework.boot:spring-boot-starter-test')
}

添加基础接口

  • 添加 Model
@Data
@Builder
@Document
@AllArgsConstructor
@NoArgsConstructor
public class Post {

    @Id
    private String id;

    private String title;

    private String content;

    @CreatedDate
    private Date createDate;
}
  • 添加 Repository
public interface PostRepository extends MongoRepository<Post, String> {
}
  • 添加配置
# MongoDB Config
spring.data.mongodb.host=localhost
spring.data.mongodb.port=27017
#spring.data.mongodb.username=
#spring.data.mongodb.password=
spring.data.mongodb.database=graphql
  • 添加数据初始化
@Component
@Slf4j
public class DataInitializer implements ApplicationRunner {

    @Autowired
    private PostRepository postRepository;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        List<Post> posts = initPost();
        posts.forEach(post -> log.info("Post: {}", post));
    }

    private List<Post> initPost() {
        postRepository.deleteAll();

        return Stream.of("Post one", "Post two")
                .map(title -> {
                    Post post = Post.builder()
                            .title(title)
                            .content("Content of " + title)
                            .build();
                    return postRepository.save(post);
                })
                .collect(Collectors.toList());
    }
}

添加 GraphQL 配置

  • 添加 GraphQL 依赖
    implementation('com.graphql-java:graphql-spring-boot-starter:5.0.2')
    // 提供 UI    
    implementation('com.graphql-java:graphiql-spring-boot-starter:5.0.2')
    // 用于 Resolver    
    implementation('com.graphql-java:graphql-java-tools:5.2.4')
  • 添加接口定义脚本
# io.github.helloworlde.graphql.model.Post 对应的Model
type Post {
    id: ID,
    title: String,
    content: String,
    createDate: String
}


# io.github.helloworlde.graphql.resolver.PostMutation.updatePost 的入参 post
input PostInput{
    title: String!,
    content: String!
}

# 查询 io.github.helloworlde.graphql.resolver.PostQuery
type Query{
    posts: [Post]
    post(id: ID!): Post
}

# 修改 io.github.helloworlde.graphql.resolver.PostMutation
type Mutation{
    createPost(post: PostInput): Post!
    updatePost(id: ID!, post: PostInput): Post!
    deletePost(id: ID!): String
}

添加接口 Resolver

  • 查询 Resolver
@Component
public class PostQuery implements GraphQLQueryResolver {

    @Autowired
    private PostRepository postRepository;

    public List<Post> posts() {
        return postRepository.findAll();
    }

    public Optional<Post> post(String id) {
        return postRepository.findById(id);
    }

}
  • 修改 Resolver
@Component
public class PostMutation implements GraphQLMutationResolver {

    @Autowired
    private PostRepository postRepository;

    public Post createPost(Post post) {
        Post newPost = Post.builder()
                .title(post.getTitle())
                .content(post.getContent())
                .build();

        return postRepository.save(newPost);
    }

    public Post updatePost(String id, Post post) throws Exception {
        Post currentPost = postRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Post " + id + " Not Exist"));

        currentPost.setTitle(post.getTitle());
        currentPost.setContent(post.getContent());

        return postRepository.save(currentPost);
    }

    public String deletePost(String id) throws Exception {
        postRepository.findById(id)
                .orElseThrow(() -> new IllegalArgumentException("Post " + id + " Not Exist"));

        postRepository.deleteById(id);
        return id;
    }
}

测试

  • 启动应用

  • 访问 http://localhost:8080/graphiql

GraphQL Spring Boot 使用

查询

  • 查询列表
{
  posts {
    id
    title
    content
    createDate
  }
}
{
  "data": {
    "posts": [
      {
        "id": "5c50245b7ed65eacb3372aba",
        "title": "Post one",
        "content": "Content of Post one",
        "createDate": "Tue Jan 29 18:00:59 CST 2019"
      },
      {
        "id": "5c50245b7ed65eacb3372abb",
        "title": "Post two",
        "content": "Content of Post two",
        "createDate": "Tue Jan 29 18:00:59 CST 2019"
      }
    ]
  }
}
  • 查询指定 id
{
  post(id: "5c50245b7ed65eacb3372aba") {
    id
    title
    content
    createDate
  }
}
{
  "data": {
    "post": {
      "id": "5c50245b7ed65eacb3372aba",
      "title": "Post one",
      "content": "Content of Post one",
      "createDate": "Tue Jan 29 18:00:59 CST 2019"
    }
  }
}

修改

  • 新增
mutation {
  createPost(post: {title: "New Posts", content: "New Post Content"}) {
    id
    title
    content
    createDate
  }
}
{
  "data": {
    "createPost": {
      "id": "5c5027197ed65eaf47a0854d",
      "title": "New Posts",
      "content": "New Post Content",
      "createDate": "Tue Jan 29 18:12:41 CST 2019"
    }
  }
}
  • 修改
mutation {
  updatePost(id: "5c5027197ed65eaf47a0854d", post: {title: "Update Posts", content: "Update Post Content"}) {
    id
    title
    content
    createDate
  }
}
{
  "data": {
    "updatePost": {
      "id": "5c5027197ed65eaf47a0854d",
      "title": "Update Posts",
      "content": "Update Post Content",
      "createDate": "Tue Jan 29 18:12:41 CST 2019"
    }
  }
}
  • 删除
mutation {
  deletePost(id: "5c5027197ed65eaf47a0854d")
}
{
  "data": {
    "deletePost": "5c5027197ed65eaf47a0854d"
  }
}

参考文章

  • GraphQL
  • Spring Boot + GraphQL + MongoDB
  • graphql-spring-boot
  • learn-graphql
  • graphql-mongodb-server

推荐阅读
  • 本文详细介绍了如何在Linux系统上安装和配置Smokeping,以实现对网络链路质量的实时监控。通过详细的步骤和必要的依赖包安装,确保用户能够顺利完成部署并优化其网络性能监控。 ... [详细]
  • 本文详细介绍了 Dockerfile 的编写方法及其在网络配置中的应用,涵盖基础指令、镜像构建与发布流程,并深入探讨了 Docker 的默认网络、容器互联及自定义网络的实现。 ... [详细]
  • Explore how Matterverse is redefining the metaverse experience, creating immersive and meaningful virtual environments that foster genuine connections and economic opportunities. ... [详细]
  • CentOS7源码编译安装MySQL5.6
    2019独角兽企业重金招聘Python工程师标准一、先在cmake官网下个最新的cmake源码包cmake官网:https:www.cmake.org如此时最新 ... [详细]
  • 深入解析 Spring Security 用户认证机制
    本文将详细介绍 Spring Security 中用户登录认证的核心流程,重点分析 AbstractAuthenticationProcessingFilter 和 AuthenticationManager 的工作原理。通过理解这些组件的实现,读者可以更好地掌握 Spring Security 的认证机制。 ... [详细]
  • 本文介绍如何在现有网络中部署基于Linux系统的透明防火墙(网桥模式),以实现灵活的时间段控制、流量限制等功能。通过详细的步骤和配置说明,确保内部网络的安全性和稳定性。 ... [详细]
  • 技术分享:从动态网站提取站点密钥的解决方案
    本文探讨了如何从动态网站中提取站点密钥,特别是针对验证码(reCAPTCHA)的处理方法。通过结合Selenium和requests库,提供了详细的代码示例和优化建议。 ... [详细]
  • 如何在PHPcms网站中添加广告
    本文详细介绍了在PHPcms网站后台添加广告的方法,涵盖多种常见的广告形式,如百度广告和Google广告,并提供了相关设置的步骤。同时,文章还探讨了优化网站流量的SEO策略。 ... [详细]
  • 解决PHP与MySQL连接时出现500错误的方法
    本文详细探讨了当使用PHP连接MySQL数据库时遇到500内部服务器错误的多种解决方案,提供了详尽的操作步骤和专业建议。无论是初学者还是有经验的开发者,都能从中受益。 ... [详细]
  • 如何配置Unturned服务器及其消息设置
    本文详细介绍了Unturned服务器的配置方法和消息设置技巧,帮助用户了解并优化服务器管理。同时,提供了关于云服务资源操作记录、远程登录设置以及文件传输的相关补充信息。 ... [详细]
  • DNN Community 和 Professional 版本的主要差异
    本文详细解析了 DotNetNuke (DNN) 的两种主要版本:Community 和 Professional。通过对比两者的功能和附加组件,帮助用户选择最适合其需求的版本。 ... [详细]
  • 作为一名新手,您可能会在初次尝试使用Eclipse进行Struts开发时遇到一些挑战。本文将为您提供详细的指导和解决方案,帮助您克服常见的配置和操作难题。 ... [详细]
  • MySQL 数据库迁移指南:从本地到远程及磁盘间迁移
    本文详细介绍了如何在不同场景下进行 MySQL 数据库的迁移,包括从一个硬盘迁移到另一个硬盘、从一台计算机迁移到另一台计算机,以及解决迁移过程中可能遇到的问题。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • ASP.NET MVC中Area机制的实现与优化
    本文探讨了在ASP.NET MVC框架中,如何通过Area机制有效地组织和管理大规模应用程序的不同功能模块。通过合理的文件夹结构和命名规则,开发人员可以更高效地管理和扩展项目。 ... [详细]
author-avatar
台艾辉_435
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有