Allow adding GraphQL types to Graphene schema

This commit is contained in:
Jonathan Kim 2020-07-03 17:41:01 +01:00
parent 64af43748c
commit 8f7f2dc559
2 changed files with 49 additions and 0 deletions

View File

@ -23,6 +23,7 @@ from graphql import (
GraphQLObjectType,
GraphQLSchema,
GraphQLString,
GraphQLType,
Undefined,
)
@ -106,6 +107,11 @@ class TypeMap(dict):
def add_type(self, graphene_type):
if inspect.isfunction(graphene_type):
graphene_type = graphene_type()
# If type is a GraphQLType from graphql-core then return it immediately
if isinstance(graphene_type, GraphQLType):
return graphene_type
if isinstance(graphene_type, List):
return GraphQLList(self.add_type(graphene_type.of_type))
if isinstance(graphene_type, NonNull):

View File

@ -1,3 +1,5 @@
from textwrap import dedent
from graphql.type import (
GraphQLArgument,
GraphQLEnumType,
@ -270,3 +272,44 @@ def test_objecttype_with_possible_types():
assert graphql_type.is_type_of
assert graphql_type.is_type_of({}, None) is True
assert graphql_type.is_type_of(MyObjectType(), None) is False
def test_graphql_type():
"""Type map should allow direct GraphQL types"""
MyGraphQLType = GraphQLObjectType(
name="MyGraphQLType",
fields={
"hello": GraphQLField(GraphQLString, resolve=lambda obj, info: "world")
},
)
class Query(ObjectType):
graphql_type = Field(MyGraphQLType)
def resolve_graphql_type(root, info):
return {}
schema = Schema(query=Query)
assert str(schema) == dedent(
"""\
type Query {
graphqlType: MyGraphQLType
}
type MyGraphQLType {
hello: String
}
"""
)
results = schema.execute(
"""
query {
graphqlType {
hello
}
}
"""
)
assert not results.errors
assert results.data == {"graphqlType": {"hello": "world"}}