graphene/examples/starwars_relay/schema.py

76 lines
1.9 KiB
Python
Raw Normal View History

2015-09-26 02:35:17 +03:00
import graphene
2016-06-15 08:27:25 +03:00
from graphene import relay, resolve_only_args
2015-09-26 02:35:17 +03:00
from .data import create_ship, get_empire, get_faction, get_rebels, get_ship
2015-09-26 02:35:17 +03:00
2016-08-08 05:20:40 +03:00
class Ship(graphene.ObjectType):
2015-09-26 09:25:10 +03:00
'''A ship in the Star Wars saga'''
class Meta:
interfaces = (relay.Node, )
name = graphene.String(description='The name of the ship.')
2015-09-26 02:36:18 +03:00
2015-09-26 09:25:10 +03:00
@classmethod
2016-06-10 07:18:42 +03:00
def get_node(cls, id, context, info):
2015-10-30 10:36:31 +03:00
return get_ship(id)
2015-09-26 02:35:17 +03:00
2015-09-26 02:36:18 +03:00
class Faction(graphene.ObjectType):
2015-09-26 09:25:10 +03:00
'''A faction in the Star Wars saga'''
class Meta:
interfaces = (relay.Node, )
name = graphene.String(description='The name of the faction.')
2016-06-15 09:48:25 +03:00
ships = relay.ConnectionField(Ship, description='The ships used by the faction.')
@resolve_only_args
def resolve_ships(self, **args):
# Transform the instance ship_ids into real instances
return [get_ship(ship_id) for ship_id in self.ships]
2015-09-26 02:35:17 +03:00
2015-09-26 09:25:10 +03:00
@classmethod
2016-06-10 07:18:42 +03:00
def get_node(cls, id, context, info):
2015-10-30 10:36:31 +03:00
return get_faction(id)
class IntroduceShip(relay.ClientIDMutation):
2015-10-30 10:36:31 +03:00
class Input:
ship_name = graphene.String(required=True)
faction_id = graphene.String(required=True)
2015-10-30 10:36:31 +03:00
ship = graphene.Field(Ship)
faction = graphene.Field(Faction)
@classmethod
2016-06-10 07:18:42 +03:00
def mutate_and_get_payload(cls, input, context, info):
ship_name = input.get('shipName')
faction_id = input.get('factionId')
2015-10-30 10:36:31 +03:00
ship = create_ship(ship_name, faction_id)
faction = get_faction(faction_id)
return IntroduceShip(ship=ship, faction=faction)
2015-09-26 02:35:17 +03:00
class Query(graphene.ObjectType):
2015-09-26 09:25:10 +03:00
rebels = graphene.Field(Faction)
empire = graphene.Field(Faction)
2016-06-10 08:37:20 +03:00
node = relay.Node.Field()
2015-09-26 02:35:17 +03:00
@resolve_only_args
2015-09-26 09:25:10 +03:00
def resolve_rebels(self):
2015-10-30 10:36:31 +03:00
return get_rebels()
2015-09-26 02:35:17 +03:00
@resolve_only_args
2015-09-26 09:25:10 +03:00
def resolve_empire(self):
2015-10-30 10:36:31 +03:00
return get_empire()
class Mutation(graphene.ObjectType):
2016-06-10 08:37:20 +03:00
introduce_ship = IntroduceShip.Field()
2016-06-10 07:18:42 +03:00
2015-09-26 02:35:17 +03:00
2016-06-10 07:18:42 +03:00
schema = graphene.Schema(query=Query, mutation=Mutation)