Skip to content

Instantly share code, notes, and snippets.

@patrys
Created July 4, 2018 17:29
Show Gist options
  • Save patrys/722790e7ffb7df2208287623c0ab07e3 to your computer and use it in GitHub Desktop.
Save patrys/722790e7ffb7df2208287623c0ab07e3 to your computer and use it in GitHub Desktop.
Apollo-Server in Python
import datetime
from graphql import GraphQLObjectType, GraphQLScalarType, GraphQLSchema, graphql, parse
from graphql.execution.base import ResolveInfo
from graphql.utils.build_ast_schema import build_ast_schema
def build_schema(schema_description: str):
ast_schema = parse(schema_description)
return build_ast_schema(ast_schema)
def execute_request(schema: GraphQLSchema, query: str, root_value: any=None):
query_ast = parse(query)
return graphql(schema, query_ast, root_value)
def default_resolver(context, info: ResolveInfo):
if isinstance(context, dict):
return context.get(info.field_name)
return getattr(context, info.field_name, None)
def make_schema_executable(schema: GraphQLSchema, resolvers: dict) -> GraphQLSchema:
for type_name, type_object in schema.get_type_map().items():
if isinstance(type_object, GraphQLScalarType):
serializer = resolvers.get(type_name, type_object.serialize)
print(type_name, serializer)
type_object.serialize = serializer
if isinstance(type_object, GraphQLObjectType):
type_resolver = resolvers.get(type_name, {})
for field_name, field_object in type_object.fields.items():
field_resolver = type_resolver.get(field_name) or default_resolver
field_object.resolver = field_resolver
TEST_SCHEMA = """
schema {
query: Query
mutation: Mutation
}
type Mutation {
getToday: Date
addNumbers(a: Int, b: Int): Int
}
scalar Date
type Query {
str: String
int: Int
float: Float
id: ID
bool: Boolean
person: Person
}
type Person {
firstName: String
fullName: String
lastName: String
}
"""
TEST_QUERY = """
query {
str
bool
id
int
person {
fullName
}
}
"""
TEST_MUTATION = """
mutation {
today: getToday
addNumbers(a: 1, b: 2)
}
"""
TEST_RESOLVERS = {
'Date': lambda date: date.isoformat(),
'Mutation': {
'addNumbers': lambda *_, a, b: a + b,
'getToday': lambda *_: datetime.date.today()
},
'Query': {
'str': lambda *_: 'hello world',
'int': lambda *_: 5,
'person': lambda *_: {'firstName': 'John', 'lastName': 'Doe'}
},
'Person': {
'fullName': lambda person, *_: '%s %s' % (person['firstName'], person['lastName'])
}
}
schema = build_schema(TEST_SCHEMA)
make_schema_executable(schema, TEST_RESOLVERS)
x = execute_request(schema, TEST_QUERY, {'bool': True})
print(x.data)
x = execute_request(schema, TEST_MUTATION)
print(x.data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment