• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

helloworlde/spring-boot-graphql-demo: Basic demo of GraphQL with SpringBoot

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称(OpenSource Name):

helloworlde/spring-boot-graphql-demo

开源软件地址(OpenSource Url):

https://github.com/helloworlde/spring-boot-graphql-demo

开源编程语言(OpenSource Language):

Java 100.0%

开源软件介绍(OpenSource Introduction):

GraphQL Spring Boot basic usage

中文

Create a basic demo application by SpringBoot and GraphQL, save data in MongoDB

Create Application

  • Add dependencies
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')
}

Add Interface

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

    @Id
    private String id;

    private String title;

    private String content;

    @CreatedDate
    private Date createDate;
}
  • Add Repository
public interface PostRepository extends MongoRepository<Post, String> {
}
  • Modify Configuration
# 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
  • Add data initializer
@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());
    }
}

Configure GraphQL

  • Add dependencies of GraphQL
    implementation('com.graphql-java:graphql-spring-boot-starter:5.0.2')
    // Provide UI    
    implementation('com.graphql-java:graphiql-spring-boot-starter:5.0.2')
    // For Resolver    
    implementation('com.graphql-java:graphql-java-tools:5.2.4')
  • Add GraphQL definition script post.grahpqls
# io.github.helloworlde.graphql.model.Post corresponding Model
type Post {
    id: ID,
    title: String,
    content: String,
    createDate: String
}


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

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

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

Add Interface Resolver

  • Query 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);
    }

}
  • Modify 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;
    }
}

Test

GraphQL

Query

  • Query List
{
  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"
      }
    ]
  }
}
  • Query Specified Post by 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"
    }
  }
}

Modify

  • Create
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"
    }
  }
}
  • Update
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"
    }
  }
}
  • Delete
mutation {
  deletePost(id: "5c5027197ed65eaf47a0854d")
}
{
  "data": {
    "deletePost": "5c5027197ed65eaf47a0854d"
  }
}

References




鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap