Enum은 unique, constant 값을 설정하기 위해 사용하는 GraphQL 타입이다.
- 아래와 같이 Episode
enum class를 만들 수 있다.
방법 1
import graphene
class Episode(graphene.Enum):
NEWHOPE = 4
EMPIRE = 5
JEDI = 6
방법 2
Episode = graphene.Enum('Episode', [('NEWHOPE', 4), ('EMPIRE', 5), ('JEDI', 6)])
만약 사용하려는 Enum이 이미 정의되어 있다면 Enum.from_enum
함수를 이용해 재사용 할 수 있다.
방법 1
graphene.Enum.from_enum(AlreadyExistingPyEnum)
방법 2
# 람다 함수 이용
graphene.Enum.from_enum(
AlreadyExistingPyEnum,
description=lambda v: return 'foo' if v == AlreadyExistingPyEnum.Foo else 'bar'
)
Interface
import graphene
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
friends = graphene.List(lambda: Character)
타입 구현
Human
, Droid
의 두 가지 타입을 구현할 때 interface로 Character
를 사용하는 경우 Human
, Droid
타입 각각은 id
, name
, friends
세 필드를 반드시 포함하게 된다.starships
, home_planet
과 primary_function
을 갖는다.class Human(graphene.ObjectType):
class Meta:
interfaces = (Character, )
starships = graphene.List(Starship)
home_planet = graphene.String()
class Droid(graphene.ObjectType):
class Meta:
interfaces = (Character, )
primary_function = graphene.String()
스키마
hero
필드의 타입을 결정할 수 있다.Human
타입을 반환하게 되며 해당 타입은 Character
interface로 구현되어 있다.class Query(graphene.ObjectType):
hero = graphene.Field(
Character,
required=True,
episode=graphene.Int(required=True)
)
def resolve_hero(root, info, episode):
# Luke is the hero of Episode V
if episode == 5:
return get_human(name='Luke Skywalker')
return get_droid(name='R2-D2')
schema = graphene.Schema(query=Query, types=[Human, Droid])
resolve_type
을 정의하지 않으면 GraphQL types가 아니라 장고에서 사용하는 Graphene type에 대한 instance를 반환하게 된다는 것이다.classmethod
로 resolve_type
을 정의하는 것이 좋다.Interface with resolve type 예시
class Character(graphene.Interface):
id = graphene.ID(required=True)
name = graphene.String(required=True)
@classmethod
def resolve_type(cls, instance, info):
if instance.type == 'DROID':
return Droid
return Human