type Query {
bookById(id: ID): Book
}
type Book {
id: ID
name: String
pageCount: Int
author: Author
}
type Author {
id: ID
firstName: String
lastName: String
}
bookDetails/Book.java
코드를 다음과 같이 작성합니다package com.graphqljava.tutorial.bookDetails;
import java.util.Arrays;
import java.util.List;
record Book(String id, String name, int pageCount, String authorId) {
private static List<Book> books = Arrays.asList(
new Book("book-1", "Harry Potter and the Philosopher's Stone", 223, "author-1"),
new Book("book-2", "Moby Dick", 635, "author-2"),
new Book("book-3", "Interview with the vampire", 371, "author-3")
);
public static Book getById(String id) {
return books.stream().filter(book -> book.id().equals(id)).findFirst().orElse(null);
}
}
bookDetails/Author.java
코드를 다음과 같이 작성합니다package com.graphqljava.tutorial.bookDetails;
import java.util.Arrays;
import java.util.List;
record Author(String id, String firstName, String lastName) {
private static List<Author> authors = Arrays.asList(
new Author("author-1", "Joanne", "Rowling"),
new Author("author-2", "Herman", "Melville"),
new Author("author-3", "Anne", "Rice")
);
public static Author getById(String id) {
return authors.stream().filter(author -> author.id().equals(id)).findFirst().orElse(null);
}
}
Spring for GraphQL
은 특정 GraphQL 필드에 대한 데이터를 가져오는 메서드 핸들러에 대한 어노테이션 기반 프로그래밍 모델을 제공합니다bookDetails/BookController.java
코드를 작성합니다package com.graphqljava.tutorial.bookDetails;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.graphql.data.method.annotation.SchemaMapping;
import org.springframework.stereotype.Controller;
@Controller
class BookController {
@QueryMapping
public Book bookById(@Argument String id) {
return Book.getById(id);
}
@SchemaMapping
public Author author(Book book) {
return Author.getById(book.authorId());
}
}
@QueryMapping
bookById
에서 결정됩니다. Spring for GraphQL
은 RuntimeWiring.Builder
를 사용하여 핸들러 메서드를 graphql.schema.DataFetcher
로 등록하고 쿼리 필드인 bookById로 설정합니다.DataFetchingEnvironment
은 필드별 인자 값에 대한 맵에 접근할 수 있습니다. @Argument
어노테이션을 사용하여 인자를 대상 객체에 바인딩하고 핸들러 메서드에 주입할 수 있습니다. @SchemaMapping
어노테이션은 핸들러 메서드를 GraphQL 스키마의 필드에 매핑하고 해당 필드의 DataFetcher
로 선언합니다. spring.graphql.graphiql.enabled=true
/graphiql
에서 GraphiQL이 활성화됩니다spring.graphql.graphiql.path
를 통해 변경할 수 있습니다query bookDetails {
bookById(id: "book-1") {
id
name
pageCount
author {
id
firstName
lastName
}
}
}
참고