0Pricing
GraphQL APIs with Spring Boot · 강의

인터페이스와 유니온 타입 구현

유연하고 다형적인 스키마를 설계하기 위해 인터페이스와 유니온 타입을 활용합니다.

인터페이스와 유니온 타입 구현은(는) CoddyKit의 무료 GraphQL APIs with Spring Boot 강의입니다. 이것은 4개 중 2번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 GraphQL APIs with Spring Boot 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

Flexible Schemas with Polymorphism

GraphQL allows you to design highly flexible APIs. Sometimes, you need a field that can return different types of objects, or you want to define a shared set of fields that multiple types must implement. This is where polymorphism comes in.

We'll explore two key concepts for achieving this: Interfaces and Union Types.

Understanding GraphQL Interfaces

Imagine you have different types of media, like a Book and a Movie. Both might have a title and a releaseYear. Instead of duplicating these fields, you can define an Interface.

An interface is a contract that specifies a set of fields that any type implementing it must include. It's like a blueprint for common functionality.

Defining an Interface in SDL

In GraphQL's Schema Definition Language (SDL), an interface is defined using the interface keyword. Here, we define a Media interface that both Book and Movie will share.

interface Media {
  id: ID!
  title: String!
  releaseYear: Int
}

Types Implementing an Interface

Now, let's make our Book and Movie types implement the Media interface. They must include all fields defined by Media, and can add their own unique fields. Notice the implements keyword.

type Book implements Media {
  id: ID!
  title: String!
  releaseYear: Int
  author: String
  pages: Int
}

type Movie implements Media {
  id: ID!
  title: String!
  releaseYear: Int
  director: String
  durationMinutes: Int
}

Resolvers for Interfaces

When you query a field that returns an interface type, Spring GraphQL automatically resolves the concrete type based on the data. You usually create Java data classes that implement a common Java interface, and Spring GraphQL handles the rest. Try running this example:

package com.coddykit.graphql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

import java.util.List;
import java.util.ArrayList;

@SpringBootApplication
public class GraphqlApp {
    public static void main(String[] args) {
        SpringApplication.run(GraphqlApp.class, args);
    }
}

interface Media {
    String getId();
    String getTitle();
    Integer getReleaseYear();
}

record Book(String id, String title, Integer releaseYear, String author, Integer pages) implements Media {}
record Movie(String id, String title, Integer releaseYear, String director, Integer durationMinutes) implements Media {}

@Controller
class MediaController {

    @QueryMapping
    public List<Media> allMedia() {
        List<Media> mediaList = new ArrayList<>();
        mediaList.add(new Book("b1", "The Hitchhiker's Guide", 1979, "Douglas Adams", 193));
        mediaList.add(new Movie("m1", "Inception", 2010, "Christopher Nolan", 148));
        return mediaList;
    }
}

Exploring GraphQL Union Types

While interfaces ensure types share common fields, Union Types allow a field to return one of several distinct types, without requiring them to share any common fields. Think of it as an 'either-or' situation. For example, a search result might be a Product OR a User.

Schema Definition for Unions

In SDL, union types are defined using the union keyword, followed by the types it can represent, separated by a vertical bar |. Here's a SearchResult union that can be either a Book or a Movie.

union SearchResult = Book | Movie

Resolvers for Union Types

When a field returns a union type, Spring GraphQL needs to know which concrete type it is. For Java, you simply return an instance of one of the types defined in the union. Spring GraphQL automatically adds the __typename field for clients to distinguish. Try running this example:

package com.coddykit.graphql;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.graphql.data.method.annotation.Argument;
import org.springframework.graphql.data.method.annotation.QueryMapping;
import org.springframework.stereotype.Controller;

@SpringBootApplication
public class GraphqlApp {
    public static void main(String[] args) {
        SpringApplication.run(GraphqlApp.class, args);
    }
}

record Book(String id, String title, Integer releaseYear, String author, Integer pages) {}
record Movie(String id, String title, Integer releaseYear, String director, Integer durationMinutes) {}

@Controller
class SearchController {

    @QueryMapping
    public Object search(@Argument String query) {
        if (query.equalsIgnoreCase("inception")) {
            return new Movie("m1", "Inception", 2010, "Christopher Nolan", 148);
        } else if (query.equalsIgnoreCase("hitchhiker")) {
            return new Book("b1", "The Hitchhiker's Guide", 1979, "Douglas Adams", 193);
        }
        return null;
    }
}

Choosing Between Interfaces and Unions

Both interfaces and unions offer polymorphism, but they serve different purposes:

  • Interfaces: Use when multiple types share a common set of fields and behavior. They enforce a contract.
  • Union Types: Use when a field can return one of several distinct types that do not necessarily share any common fields. It's about 'either A or B or C'.

Interfaces vs. Unions Quiz

You are designing a GraphQL API. You need a field that can return either a Photo object or a Video object. These two types have completely different fields and do not share any common properties. Which GraphQL schema feature is best suited for this scenario?

Recap: Flexible Schemas

You've learned how GraphQL Interfaces and Union Types enable flexible and polymorphic schema designs. Interfaces define a contract for common fields, while Union Types allow a field to return one of several distinct types. These tools are crucial for building robust and adaptable GraphQL APIs.

Next, you'll explore Input Types to streamline mutation arguments.

자주 묻는 질문

“인터페이스와 유니온 타입 구현” 강의는 무료인가요?

네 — “인터페이스와 유니온 타입 구현” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 GraphQL APIs with Spring Boot 강의 전체를 잠금 해제할 수 있습니다. GraphQL APIs with Spring Boot 강의에는 총 4개의 강의가 포함되어 있습니다.

“인터페이스와 유니온 타입 구현”에서 뭘 배우나요?

유연하고 다형적인 스키마를 설계하기 위해 인터페이스와 유니온 타입을 활용합니다. 브라우저에서 직접 실행하는 실습 코드로 GraphQL APIs with Spring Boot을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

GraphQL APIs with Spring Boot을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 GraphQL APIs with Spring Boot은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 2번째 강의입니다.

“인터페이스와 유니온 타입 구현” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 GraphQL APIs with Spring Boot 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 GraphQL APIs with Spring Boot 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. 중첩 객체 및 관계 모델링
  2. 인터페이스와 유니온 타입 구현
  3. 변이에 입력 타입 활용하기
  4. 열거형과 사용자 지정 스칼라 타입
← GraphQL APIs with Spring Boot(으)로 돌아가기