From 8f7f2dc5593d33d1c064e99aca55695716fa060a Mon Sep 17 00:00:00 2001 From: Jonathan Kim Date: Fri, 3 Jul 2020 17:41:01 +0100 Subject: [PATCH] Allow adding GraphQL types to Graphene schema --- graphene/types/schema.py | 6 ++++ graphene/types/tests/test_type_map.py | 43 +++++++++++++++++++++++++++ 2 files changed, 49 insertions(+) diff --git a/graphene/types/schema.py b/graphene/types/schema.py index ce0c7439..2d1eaf6b 100644 --- a/graphene/types/schema.py +++ b/graphene/types/schema.py @@ -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): diff --git a/graphene/types/tests/test_type_map.py b/graphene/types/tests/test_type_map.py index 334eb241..41327211 100644 --- a/graphene/types/tests/test_type_map.py +++ b/graphene/types/tests/test_type_map.py @@ -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"}}