graphene/tests/starwars/schema.py

67 lines
1.7 KiB
Python
Raw Normal View History

from graphql.core.type import GraphQLEnumValue
2015-09-24 12:11:50 +03:00
import graphene
from graphene import resolve_only_args
from .data import getHero, getHuman, getCharacter, getDroid, Human as _Human, Droid as _Droid
Episode = graphene.Enum('Episode', dict(
NEWHOPE=GraphQLEnumValue(4),
EMPIRE=GraphQLEnumValue(5),
JEDI=GraphQLEnumValue(6)
2015-09-24 12:11:50 +03:00
))
2015-09-26 06:01:14 +03:00
2015-09-24 12:11:50 +03:00
def wrap_character(character):
2015-10-03 08:17:51 +03:00
if isinstance(character, _Human):
2015-09-24 12:11:50 +03:00
return Human(character)
elif isinstance(character, _Droid):
return Droid(character)
2015-09-26 06:01:14 +03:00
2015-09-24 12:11:50 +03:00
class Character(graphene.Interface):
id = graphene.IDField()
name = graphene.StringField()
2015-09-26 06:01:14 +03:00
friends = graphene.ListField('self')
2015-09-24 12:11:50 +03:00
appearsIn = graphene.ListField(Episode)
def resolve_friends(self, args, *_):
return [wrap_character(getCharacter(f)) for f in self.instance.friends]
2015-09-26 06:01:14 +03:00
2015-09-24 12:11:50 +03:00
class Human(Character):
homePlanet = graphene.StringField()
class Droid(Character):
primaryFunction = graphene.StringField()
class Query(graphene.ObjectType):
hero = graphene.Field(Character,
2015-10-03 08:17:51 +03:00
episode=graphene.Argument(Episode)
)
2015-09-24 12:11:50 +03:00
human = graphene.Field(Human,
2015-10-03 08:17:51 +03:00
id=graphene.Argument(graphene.String)
)
2015-09-24 12:11:50 +03:00
droid = graphene.Field(Droid,
2015-10-03 08:17:51 +03:00
id=graphene.Argument(graphene.String)
)
2015-09-24 12:11:50 +03:00
2015-09-26 13:36:00 +03:00
class Meta:
type_name = 'core_Query'
2015-09-26 13:36:00 +03:00
2015-09-24 12:11:50 +03:00
@resolve_only_args
2015-10-07 08:53:43 +03:00
def resolve_hero(self, episode=None):
2015-09-24 12:11:50 +03:00
return wrap_character(getHero(episode))
@resolve_only_args
def resolve_human(self, id):
return wrap_character(getHuman(id))
@resolve_only_args
def resolve_droid(self, id):
return wrap_character(getDroid(id))
Schema = graphene.Schema(query=Query)