Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 9 additions & 16 deletions src/main/kotlin/graphql/kickstart/tools/ResolverInfo.kt
Original file line number Diff line number Diff line change
Expand Up @@ -48,26 +48,19 @@ internal class NormalResolverInfo(
}
}

internal class MultiResolverInfo(val resolverInfoList: List<NormalResolverInfo>) : DataClassTypeResolverInfo, ResolverInfo() {
override val dataClassType = findDataClass()

/**
* Checks if all `ResolverInfo` instances are related to the same data type
*/
private fun findDataClass(): Class<out Any> {
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<NormalResolverInfo>,
override val dataClassType: Class<out Any>
) : DataClassTypeResolverInfo, ResolverInfo() {

override fun getFieldSearches(): List<FieldResolverScanner.Search> {
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()
}
Expand Down
47 changes: 30 additions & 17 deletions src/main/kotlin/graphql/kickstart/tools/SchemaClassScanner.kt
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -28,7 +29,6 @@ internal class SchemaClassScanner(
private val subscriptionResolvers = resolvers.filterIsInstance<GraphQLSubscriptionResolver>()

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<ObjectTypeExtensionDefinition>()
Expand Down Expand Up @@ -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)
Expand Down
146 changes: 146 additions & 0 deletions src/test/kotlin/graphql/kickstart/tools/SupertypeResolverTest.kt
Original file line number Diff line number Diff line change
@@ -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<Base> {
fun isActive(base: Base): Boolean = true
fun label(base: Base): String = "base label"
}

class NamedResolver : GraphQLResolver<Named> {
fun label(named: Named): String = "named label"
fun description(named: Named): String = "named description"
}

class OtherThingResolver : GraphQLResolver<OtherThing> {
fun isActive(otherThing: OtherThing): Boolean = false
fun label(otherThing: OtherThing): String = "other label"
}
}
Loading