graphene/tests/starwars_relay/schema.py

62 lines
1.6 KiB
Python
Raw Normal View History

2015-09-26 02:35:17 +03:00
import graphene
2015-09-26 02:36:18 +03:00
from graphene import resolve_only_args, relay
2015-09-26 02:35:17 +03:00
2015-09-26 02:36:18 +03:00
from .data import (
getHero, getHuman, getCharacter, getDroid,
Human as _Human, Droid as _Droid)
2015-09-26 02:35:17 +03:00
Episode = graphene.Enum('Episode', dict(
2015-09-26 02:36:18 +03:00
NEWHOPE=4,
EMPIRE=5,
JEDI=6
2015-09-26 02:35:17 +03:00
))
2015-09-26 02:36:18 +03:00
2015-09-26 02:35:17 +03:00
def wrap_character(character):
2015-09-26 02:36:18 +03:00
if isinstance(character, _Human):
2015-09-26 02:35:17 +03:00
return Human(character)
elif isinstance(character, _Droid):
return Droid(character)
2015-09-26 02:36:18 +03:00
2015-09-26 02:35:17 +03:00
class Character(graphene.Interface):
name = graphene.StringField()
2015-09-26 05:41:11 +03:00
friends = relay.Connection('Character')
2015-09-26 02:35:17 +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 02:36:18 +03:00
class Human(relay.Node, Character):
2015-09-26 02:35:17 +03:00
homePlanet = graphene.StringField()
2015-09-26 02:36:18 +03:00
class Droid(relay.Node, Character):
2015-09-26 02:35:17 +03:00
primaryFunction = graphene.StringField()
class Query(graphene.ObjectType):
hero = graphene.Field(Character,
2015-09-26 02:36:18 +03:00
episode=graphene.Argument(Episode))
2015-09-26 02:35:17 +03:00
human = graphene.Field(Human,
2015-09-26 02:36:18 +03:00
id=graphene.Argument(graphene.String))
2015-09-26 02:35:17 +03:00
droid = graphene.Field(Droid,
2015-09-26 02:36:18 +03:00
id=graphene.Argument(graphene.String))
node = graphene.Field(relay.Node)
2015-09-26 02:35:17 +03:00
@resolve_only_args
def resolve_hero(self, episode):
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)