From 0d251249a4ebdc069a4468fe6529987246178af9 Mon Sep 17 00:00:00 2001 From: Tim Griesser Date: Sat, 26 Nov 2016 11:08:51 -0500 Subject: [PATCH] Allow resolve_type to return a type name string --- graphql/execution/executor.py | 4 ++ graphql/execution/tests/test_abstract.py | 66 ++++++++++++++++++++++++ 2 files changed, 70 insertions(+) diff --git a/graphql/execution/executor.py b/graphql/execution/executor.py index 015b8a76..7d08db32 100644 --- a/graphql/execution/executor.py +++ b/graphql/execution/executor.py @@ -3,6 +3,7 @@ import logging import sys +from six import string_types from promise import Promise, promise_for_dict, promisify, is_thenable from ..error import GraphQLError, GraphQLLocatedError @@ -325,6 +326,9 @@ def complete_abstract_value(exe_context, return_type, field_asts, info, result): else: runtime_type = get_default_resolve_type_fn(result, exe_context.context_value, info, return_type) + if isinstance(runtime_type, string_types): + runtime_type = info.schema.get_type(runtime_type) + if not isinstance(runtime_type, GraphQLObjectType): raise GraphQLError( ('Abstract type {} must resolve to an Object type at runtime ' + diff --git a/graphql/execution/tests/test_abstract.py b/graphql/execution/tests/test_abstract.py index d7ca41f4..b58920f2 100644 --- a/graphql/execution/tests/test_abstract.py +++ b/graphql/execution/tests/test_abstract.py @@ -295,3 +295,69 @@ def test_resolve_type_on_union_yields_useful_error(): result = graphql(schema, query) assert result.errors[0].message == 'Runtime Object type "Human" is not a possible type for "Pet".' assert result.data == {'pets': [{'woofs': True, 'name': 'Odie'}, {'name': 'Garfield', 'meows': False}, None]} + + +def test_resolve_type_can_use_type_string(): + + def type_string_resolver(obj, *_): + if isinstance(obj, Dog): + return 'Dog' + if isinstance(obj, Cat): + return 'Cat' + + PetType = GraphQLInterfaceType( + name='Pet', + fields={ + 'name': GraphQLField(GraphQLString) + }, + resolve_type=type_string_resolver + ) + + DogType = GraphQLObjectType( + name='Dog', + interfaces=[PetType], + fields={ + 'name': GraphQLField(GraphQLString), + 'woofs': GraphQLField(GraphQLBoolean) + } + ) + + CatType = GraphQLObjectType( + name='Cat', + interfaces=[PetType], + fields={ + 'name': GraphQLField(GraphQLString), + 'meows': GraphQLField(GraphQLBoolean) + } + ) + + schema = GraphQLSchema( + query=GraphQLObjectType( + name='Query', + fields={ + 'pets': GraphQLField( + GraphQLList(PetType), + resolver=lambda *_: [Dog('Odie', True), Cat('Garfield', False)] + ) + } + ), + types=[CatType, DogType] + ) + + query = ''' + { + pets { + name + ... on Dog { + woofs + } + ... on Cat { + meows + } + } + } + ''' + + result = graphql(schema, query) + assert not result.errors + assert result.data == {'pets': [{'woofs': True, 'name': 'Odie'}, {'name': 'Garfield', 'meows': False}]}