graphene/examples/starwars_relay/schema.py

79 lines
1.9 KiB
Python
Raw Normal View History

2015-09-26 02:35:17 +03:00
import graphene
2017-07-27 12:51:25 +03:00
from graphene import relay
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):
"""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
2017-07-28 06:06:48 +03:00
def get_node(cls, info, id):
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
2017-07-13 07:21:16 +03:00
class ShipConnection(relay.Connection):
class Meta:
node = Ship
class Faction(graphene.ObjectType):
"""A faction in the Star Wars saga"""
class Meta:
interfaces = (relay.Node,)
name = graphene.String(description="The name of the faction.")
ships = relay.ConnectionField(
ShipConnection, description="The ships used by the faction."
)
2016-06-15 09:48:25 +03:00
2017-07-27 12:51:25 +03:00
def resolve_ships(self, info, **args):
2016-06-15 09:48:25 +03:00
# 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
2017-07-28 06:06:48 +03:00
def get_node(cls, info, id):
2015-10-30 10:36:31 +03:00
return get_faction(id)
class IntroduceShip(relay.ClientIDMutation):
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
def mutate_and_get_payload(
cls, root, info, ship_name, faction_id, client_mutation_id=None
):
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
2017-07-27 12:51:25 +03:00
def resolve_rebels(self, info):
2015-10-30 10:36:31 +03:00
return get_rebels()
2015-09-26 02:35:17 +03:00
2017-07-27 12:51:25 +03:00
def resolve_empire(self, info):
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)