ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • GraphQL 사용해보기!
    엘리스트랙 2024. 4. 14. 15:09
    728x90

     

     

     

     

    도서 정보를 가져오는 api를 만들어보자

     

    일단 GraphQL 파일을 생성해 스키마를 정의한다.

     

    type Query {
        bookById(id: ID): Book
    }
    
    type Book {
        id: ID
        name: String
        pageCount: Int
        author: Author
    }
    
    type Author {
        id: ID
        firstName: String
        lastName: String
    }

     

     

    그리고 Book 클래스와 Author 클래스를 생성한다.

     

    import java.util.Arrays;
    import java.util.List;
    
    public record Book (String id, String name, int pageCount, String authorId) {
    
        public static List<Book> books = Arrays.asList(
                new Book("book-1", "Effective Java", 416, "author-1"),
                new Book("book-2", "Hitchhiker's Guide to the Galaxy", 208, "author-2"),
                new Book("book-3", "Down Under", 436, "author-3")
        );
    
        public static Book getById(String id) {
            return books.stream()
    				.filter(book -> book.id().equals(id))
    				.findFirst()
    				.orElse(null);
        }
    }

     

     

    import java.util.Arrays;
    import java.util.List;
    
    public record Author (String id, String firstName, String lastName) {
    
        public static List<Author> authors = Arrays.asList(
                new Author("author-1", "Joshua", "Bloch"),
                new Author("author-2", "Douglas", "Adams"),
                new Author("author-3", "Bill", "Bryson")
        );
    
        public static Author getById(String id) {
            return authors.stream()
    				.filter(author -> author.id().equals(id))
    				.findFirst()
    				.orElse(null);
        }
    }

     

     

    그리고 컨트롤러를 생성해 원하는 GraphQL 필드의 데이터를 가져온다.

     

    package com.example.graphqlserver;
    
    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
    public 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 어노테이션은 메서드가 GraphQL 쿼리 요청을 처리하는 엔드포인트임을 나타내고 스키마 부분에서 bookById의 쿼리 요청을 처리한다.

     

    @SchemaMapping 어노테이션이 붙은 author 메서드는 Book 타입의 객체를 받아 그 책의 저자 정보를 반환하는 리졸버로 동작합니다. 여기서는 Book 객체의 authorId를 사용하여 저자 정보를 조회합니다.

     

     

    그럼 이 쿼리의 작동을 테스트해보자.

     

    application.properties에 spring.graphql.graphiql.enabled=true을 추가하면 GraphiQL를 실행할 수 있다.

     

    Spring 애플리케이션을 시작하고

    http://localhost:8080/graphiql로 이동하면 쿼리를 실행할 수 있는 창이 나온다.

     

     

     

    검색 쿼리를 실행한 모습이다. 

     

     

     

    728x90

    '엘리스트랙' 카테고리의 다른 글

    최종 프로젝트 기획!  (1) 2024.04.21
    스프링 웹소켓 복습!  (0) 2024.04.14
    GraphQL이란?  (0) 2024.04.14
    도커 파일과 컴포즈!  (1) 2024.04.07
    도커 실행해보기!  (0) 2024.04.07
Designed by Tistory.