diff --git a/src/main/kotlin/graphql/kickstart/tools/ResolverInfo.kt b/src/main/kotlin/graphql/kickstart/tools/ResolverInfo.kt index 63016fa1..267feb21 100644 --- a/src/main/kotlin/graphql/kickstart/tools/ResolverInfo.kt +++ b/src/main/kotlin/graphql/kickstart/tools/ResolverInfo.kt @@ -48,26 +48,19 @@ internal class NormalResolverInfo( } } -internal class MultiResolverInfo(val resolverInfoList: List) : DataClassTypeResolverInfo, ResolverInfo() { - override val dataClassType = findDataClass() - - /** - * Checks if all `ResolverInfo` instances are related to the same data type - */ - private fun findDataClass(): Class { - val dataClass = resolverInfoList.asSequence().map { it.dataClassType }.distinct().singleOrNull() - - if (dataClass == null) { - throw ResolverError("Resolvers may not use the same type.") - } else { - return dataClass - } - } +/** + * Combines all resolvers that apply to a data class, i.e. resolvers for the data class itself and for any of its supertypes. + * Resolvers are searched in the given order, followed by the data class itself. + */ +internal class MultiResolverInfo( + val resolverInfoList: List, + override val dataClassType: Class +) : DataClassTypeResolverInfo, ResolverInfo() { override fun getFieldSearches(): List { return resolverInfoList .asSequence() - .map { FieldResolverScanner.Search(it.resolverType, this, it.resolver, dataClassType) } + .map { FieldResolverScanner.Search(it.resolverType, this, it.resolver, it.dataClassType) } .plus(FieldResolverScanner.Search(dataClassType, this, null)) .toList() } diff --git a/src/main/kotlin/graphql/kickstart/tools/SchemaClassScanner.kt b/src/main/kotlin/graphql/kickstart/tools/SchemaClassScanner.kt index 88c05a94..8d678863 100644 --- a/src/main/kotlin/graphql/kickstart/tools/SchemaClassScanner.kt +++ b/src/main/kotlin/graphql/kickstart/tools/SchemaClassScanner.kt @@ -6,6 +6,7 @@ import graphql.kickstart.tools.util.* import graphql.language.* import graphql.schema.GraphQLScalarType import graphql.schema.idl.ScalarInfo +import org.apache.commons.lang3.ClassUtils import org.slf4j.LoggerFactory import java.lang.reflect.Method @@ -28,7 +29,6 @@ internal class SchemaClassScanner( private val subscriptionResolvers = resolvers.filterIsInstance() private val resolverInfos = resolvers.asSequence().minus(queryResolvers).minus(mutationResolvers).minus(subscriptionResolvers).map { NormalResolverInfo(it, options) }.toList() - private val resolverInfosByDataClass = this.resolverInfos.associateBy { it.dataClassType } private val initialDictionary = initialDictionary.mapValues { InitialDictionaryEntry(it.value) } private val extensionDefinitions = allDefinitions.filterIsInstance() @@ -281,34 +281,47 @@ internal class SchemaClassScanner( } } + /** + * Scan a new object for types that haven't been mapped yet. + */ + private fun scanQueueItemForPotentialMatches(item: QueueItem) { + val resolverInfo = if (item.clazz == Object::class.java) { + getResolverInfoFromTypeDictionary(item.type.name) + ?: throw SchemaClassScannerError("The GraphQL schema type '${item.type.name}' maps to a field of type java.lang.Object however there is no matching entry for this type in the type dictionary. You may need to add this type to the dictionary before building the schema.") + } else { + getResolverInfoFromDataClass(item.clazz) + } + + scanResolverInfoForPotentialMatches(item.type, resolverInfo) + } + private fun getResolverInfoFromTypeDictionary(typeName: String): ResolverInfo? { val dictionaryType = initialDictionary[typeName]?.get() return if (dictionaryType != null) { - resolverInfosByDataClass[dictionaryType] ?: DataClassResolverInfo(dictionaryType) + getResolverInfoFromDataClass(dictionaryType) } else { null } } /** - * Scan a new object for types that haven't been mapped yet. + * Find all resolvers for the data class or any of its supertypes, most specific first. */ - private fun scanQueueItemForPotentialMatches(item: QueueItem) { - val resolverInfoList = this.resolverInfos.filter { it.dataClassType == item.clazz } - val resolverInfo: ResolverInfo = (if (resolverInfoList.size > 1) { - MultiResolverInfo(resolverInfoList) - } else { - if (item.clazz == Object::class.java) { - getResolverInfoFromTypeDictionary(item.type.name) - } else { - resolverInfosByDataClass[item.clazz] ?: DataClassResolverInfo(item.clazz) - } - }) - ?: throw SchemaClassScannerError("The GraphQL schema type '${item.type.name}' maps to a field of type java.lang.Object however there is no matching entry for this type in the type dictionary. You may need to add this type to the dictionary before building the schema.") - - scanResolverInfoForPotentialMatches(item.type, resolverInfo) + private fun getResolverInfoFromDataClass(dataClass: JavaType): ResolverInfo { + val resolverInfoList = resolverInfos + .filter { it.dataClassType == dataClass || isResolverForSupertype(it, dataClass) } + .sortedByDescending { ClassUtils.getAllSuperclasses(it.dataClassType).size + ClassUtils.getAllInterfaces(it.dataClassType).size } + + return when { + resolverInfoList.isEmpty() -> DataClassResolverInfo(dataClass) + resolverInfoList.size == 1 && resolverInfoList.single().dataClassType == dataClass -> resolverInfoList.single() + else -> MultiResolverInfo(resolverInfoList, dataClass.unwrap()) + } } + private fun isResolverForSupertype(resolverInfo: NormalResolverInfo, dataClass: JavaType) = + dataClass is Class<*> && resolverInfo.dataClassType != Object::class.java && resolverInfo.dataClassType.isAssignableFrom(dataClass) + private fun scanResolverInfoForPotentialMatches(type: ObjectTypeDefinition, resolverInfo: ResolverInfo) { type.getExtendedFieldDefinitions(extensionDefinitions).forEach { field -> val fieldResolver = fieldResolverScanner.findFieldResolver(field, resolverInfo) diff --git a/src/test/kotlin/graphql/kickstart/tools/SupertypeResolverTest.kt b/src/test/kotlin/graphql/kickstart/tools/SupertypeResolverTest.kt new file mode 100644 index 00000000..f3d1ef1d --- /dev/null +++ b/src/test/kotlin/graphql/kickstart/tools/SupertypeResolverTest.kt @@ -0,0 +1,146 @@ +package graphql.kickstart.tools + +import graphql.GraphQL +import graphql.execution.AsyncExecutionStrategy +import graphql.schema.GraphQLSchema +import org.junit.Test + +class SupertypeResolverTest { + + private val schema: GraphQLSchema = SchemaParser.newParser() + .schemaString( + """ + type Query { + thing: Thing! + otherThing: OtherThing! + labelledThing: LabelledThing! + } + + type Thing { + name: String! + active: Boolean! + label: String! + description: String! + } + + type OtherThing { + name: String! + active: Boolean! + label: String! + description: String! + } + + type LabelledThing { + label: String! + } + """) + .resolvers(QueryResolver(), BaseResolver(), NamedResolver(), OtherThingResolver()) + .build() + .makeExecutableSchema() + private val gql: GraphQL = GraphQL.newGraphQL(schema) + .queryExecutionStrategy(AsyncExecutionStrategy()) + .build() + + @Test + fun `resolvers for a superclass or interface should resolve fields of subclasses`() { + val data = assertNoGraphQlErrors(gql) { + """ + query { + thing { + name + active + label + description + } + } + """ + } + + assertEquals(data["thing"], mapOf( + "name" to "thing", + "active" to true, + "label" to "base label", + "description" to "named description" + )) + } + + @Test + fun `more specific resolvers should take precedence over supertype resolvers`() { + val data = assertNoGraphQlErrors(gql) { + """ + query { + otherThing { + name + active + label + description + } + } + """ + } + + assertEquals(data["otherThing"], mapOf( + "name" to "other thing", + "active" to false, + "label" to "other label", + "description" to "named description" + )) + } + + @Test + fun `supertype resolvers should take precedence over getters on the data class`() { + val data = assertNoGraphQlErrors(gql) { + """ + query { + labelledThing { + label + } + } + """ + } + + assertEquals(data["labelledThing"], mapOf( + "label" to "base label" + )) + } + + class QueryResolver : GraphQLQueryResolver { + fun thing(): Thing = Thing() + fun otherThing(): OtherThing = OtherThing() + fun labelledThing(): LabelledThing = LabelledThing() + } + + interface Named { + val name: String + } + + abstract class Base : Named + + class Thing : Base() { + override val name = "thing" + } + + class OtherThing : Base() { + override val name = "other thing" + } + + class LabelledThing : Base() { + override val name = "labelled thing" + val label = "getter label" + } + + class BaseResolver : GraphQLResolver { + fun isActive(base: Base): Boolean = true + fun label(base: Base): String = "base label" + } + + class NamedResolver : GraphQLResolver { + fun label(named: Named): String = "named label" + fun description(named: Named): String = "named description" + } + + class OtherThingResolver : GraphQLResolver { + fun isActive(otherThing: OtherThing): Boolean = false + fun label(otherThing: OtherThing): String = "other label" + } +}