Merge pull request #10270 from tomas-skalicky/fb-tomas-graphql-codefix-and-sample-queries

GraphQL code fixes and sample queries
This commit is contained in:
Loredana Crusoveanu 2020-12-26 09:53:08 +02:00 committed by GitHub
commit 22494667cd
5 changed files with 49 additions and 5 deletions

View File

@ -15,3 +15,21 @@ The "REST With Spring" Classes: http://bit.ly/restwithspring
- [Spring Boot and Togglz Aspect](https://www.baeldung.com/spring-togglz)
- [Getting Started with GraphQL and Spring Boot](https://www.baeldung.com/spring-graphql)
- [An Introduction to Kong](https://www.baeldung.com/kong)
### GraphQL sample queries
Query
```shell script
curl \
--request POST 'localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"query {\n recentPosts(count: 2, offset: 0) {\n id\n title\n author {\n id\n posts {\n id\n }\n }\n }\n}"}'
```
Mutation
```shell script
curl \
--request POST 'localhost:8081/graphql' \
--header 'Content-Type: application/json' \
--data-raw '{"query":"mutation {\n writePost(title: \"New Title\", author: \"Author2\", text: \"New Text\") {\n id\n category\n author {\n id\n name\n }\n }\n}"}'
```

View File

@ -2,12 +2,14 @@ package com.baeldung.demo;
import com.baeldung.graphql.GraphqlConfiguration;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.autoconfigure.security.servlet.SecurityAutoConfiguration;
import org.springframework.context.annotation.Import;
@SpringBootApplication
@Import(GraphqlConfiguration.class)
@EnableAutoConfiguration(exclude = {SecurityAutoConfiguration.class})
public class DemoApplication {
public static void main(String[] args) {

View File

@ -1,7 +1,5 @@
package com.baeldung.graphql;
import java.util.Optional;
import com.coxautodev.graphql.tools.GraphQLResolver;
public class PostResolver implements GraphQLResolver<Post> {
@ -11,7 +9,7 @@ public class PostResolver implements GraphQLResolver<Post> {
this.authorDao = authorDao;
}
public Optional<Author> getAuthor(Post post) {
return authorDao.getAuthor(post.getAuthorId());
public Author getAuthor(Post post) {
return authorDao.getAuthor(post.getAuthorId()).orElseThrow(RuntimeException::new);
}
}

View File

@ -0,0 +1,2 @@
server:
port: 8081

View File

@ -0,0 +1,24 @@
type Post {
id: ID!
title: String!
text: String!
category: String
author: Author!
}
type Author {
id: ID!
name: String!
thumbnail: String
posts: [Post]!
}
# The Root Query for the application
type Query {
recentPosts(count: Int, offset: Int): [Post]!
}
# The Root Mutation for the application
type Mutation {
writePost(title: String!, text: String!, category: String, author: String!) : Post!
}