Skip to content

Commit 72e6389

Browse files
authored
Implement field datafetchers and multiple root resolvers (fixes graphql-java-kickstart#35, fixes graphql-java-kickstart#40, fixes graphql-java-kickstart#42, fixes graphql-java-kickstart#45) (graphql-java-kickstart#48)
* Start reworking scanner to support property lookups and multiple root resolvers * Rework the scanner to use new constructs * Fix most compile errors in source * Remove unecessary class-level variables * Add warnings for unecessary root resolvers * Extract extension function * Fix resolver tests * Fix test * Fix all tests * Add test for multiple root resolvers * Add tests for field resolver scanner * Test warning messages * Add test for multiple interfaces that aren't used as field types (fixes graphql-java-kickstart#45) * Add failing test for graphql-java-kickstart#42 * Add support for type extensions (fixes #graphql-java-kickstart#42) * Implement property datafetcher * Only error on multiple field resolver matches for root resolvers
1 parent bc9160d commit 72e6389

25 files changed

Lines changed: 824 additions & 469 deletions
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
package com.coxautodev.graphql.tools
2+
3+
import graphql.language.FieldDefinition
4+
import graphql.schema.DataFetcher
5+
import graphql.schema.DataFetchingEnvironment
6+
7+
/**
8+
* @author Andrew Potter
9+
*/
10+
internal abstract class FieldResolver(val field: FieldDefinition, val search: FieldResolverScanner.Search, relativeTo: JavaType) {
11+
val resolverInfo: ResolverInfo = search.resolverInfo
12+
val genericType = GenericType(search.type).relativeToPotentialParent(relativeTo)
13+
14+
abstract fun scanForMatches(): List<TypeClassMatcher.PotentialMatch>
15+
abstract fun createDataFetcher(): DataFetcher<*>
16+
17+
/**
18+
* Add source resolver depending on whether or not this is a resolver method
19+
*/
20+
protected fun getSourceResolver(): SourceResolver = if(this.search.source != null) {
21+
({ this.search.source })
22+
} else {
23+
({ environment ->
24+
val source = environment.getSource<Any>()
25+
26+
if(!this.genericType.isAssignableFrom(source.javaClass)) {
27+
throw ResolverError("Expected source object to be an instance of '${this.genericType.getRawClass().name}' but instead got '${source.javaClass.name}'")
28+
}
29+
30+
source
31+
})
32+
}
33+
}
34+
35+
internal typealias SourceResolver = (DataFetchingEnvironment) -> Any
Lines changed: 127 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,127 @@
1+
package com.coxautodev.graphql.tools
2+
3+
import graphql.Scalars
4+
import graphql.language.FieldDefinition
5+
import graphql.language.TypeName
6+
import graphql.schema.DataFetchingEnvironment
7+
import org.apache.commons.lang3.ClassUtils
8+
import org.apache.commons.lang3.reflect.FieldUtils
9+
import java.lang.reflect.Field
10+
import java.lang.reflect.Method
11+
12+
/**
13+
* @author Andrew Potter
14+
*/
15+
internal class FieldResolverScanner {
16+
17+
companion object {
18+
fun getAllMethods(type: Class<*>): List<Method> {
19+
return type.declaredMethods.toList() + ClassUtils.getAllSuperclasses(type).flatMap { it.declaredMethods.toList() }
20+
}
21+
}
22+
23+
fun findFieldResolver(field: FieldDefinition, resolverInfo: ResolverInfo): FieldResolver {
24+
val searches = resolverInfo.getFieldSearches()
25+
26+
val scanProperties = field.inputValueDefinitions.isEmpty()
27+
val found = searches.mapNotNull { search -> findFieldResolver(field, search, scanProperties) }
28+
29+
if(resolverInfo is RootResolverInfo && found.size > 1) {
30+
throw FieldResolverError("Found more than one matching resolver for field '$field': $found")
31+
}
32+
33+
return found.firstOrNull() ?: throw FieldResolverError(getMissingFieldMessage(field, searches, scanProperties))
34+
}
35+
36+
private fun findFieldResolver(field: FieldDefinition, search: Search, scanProperties: Boolean): FieldResolver? {
37+
val method = findResolverMethod(field, search)
38+
if(method != null) {
39+
return MethodFieldResolver(field, search, method.apply { isAccessible = true })
40+
}
41+
42+
if(scanProperties) {
43+
val property = findResolverProperty(field, search)
44+
if(property != null) {
45+
return PropertyFieldResolver(field, search, property.apply { isAccessible = true })
46+
}
47+
}
48+
49+
return null
50+
}
51+
52+
private fun isBoolean(type: GraphQLLangType) = type.unwrap().let { it is TypeName && it.name == Scalars.GraphQLBoolean.name }
53+
54+
private fun findResolverMethod(field: FieldDefinition, search: Search): java.lang.reflect.Method? {
55+
56+
val methods = getAllMethods(search.type)
57+
val argumentCount = field.inputValueDefinitions.size + if(search.requiredFirstParameterType != null) 1 else 0
58+
val name = field.name
59+
60+
val isBoolean = isBoolean(field.type)
61+
62+
// Check for the following one by one:
63+
// 1. Method with exact field name
64+
// 2. Method that returns a boolean with "is" style getter
65+
// 3. Method with "get" style getter
66+
return methods.find {
67+
it.name == name && verifyMethodArguments(it, argumentCount, search)
68+
} ?: methods.find {
69+
(isBoolean && it.name == "is${name.capitalize()}") && verifyMethodArguments(it, argumentCount, search)
70+
} ?: methods.find {
71+
it.name == "get${name.capitalize()}" && verifyMethodArguments(it, argumentCount, search)
72+
}
73+
}
74+
75+
private fun verifyMethodArguments(method: java.lang.reflect.Method, requiredCount: Int, search: Search): Boolean {
76+
val correctParameterCount = method.parameterCount == requiredCount || (method.parameterCount == (requiredCount + 1) && method.parameterTypes.last() == DataFetchingEnvironment::class.java)
77+
val appropriateFirstParameter = if(search.requiredFirstParameterType != null) method.parameterTypes.firstOrNull() == search.requiredFirstParameterType else true
78+
return correctParameterCount && appropriateFirstParameter
79+
}
80+
81+
82+
private fun findResolverProperty(field: FieldDefinition, search: Search): Field? {
83+
return FieldUtils.getAllFields(search.type).find { it.name == field.name }
84+
}
85+
86+
fun getMissingFieldMessage(field: FieldDefinition, searches: List<Search>, scannedProperties: Boolean): String {
87+
val signatures = mutableListOf("")
88+
val isBoolean = isBoolean(field.type)
89+
90+
searches.forEach { search ->
91+
signatures.addAll(getMissingMethodSignatures(field, search, isBoolean, scannedProperties))
92+
}
93+
94+
return "No method${if(scannedProperties) " or field" else ""} found with any of the following signatures (with or without ${DataFetchingEnvironment::class.java.name} as the last argument), in priority order:\n${signatures.joinToString("\n ")}"
95+
}
96+
97+
98+
fun getMissingMethodSignatures(field: FieldDefinition, search: Search, isBoolean: Boolean, scannedProperties: Boolean): List<String> {
99+
val baseType = search.type
100+
val signatures = mutableListOf<String>()
101+
val args = mutableListOf<String>()
102+
val sep = ", "
103+
104+
if(search.requiredFirstParameterType != null) {
105+
args.add(search.requiredFirstParameterType.name)
106+
}
107+
108+
args.addAll(field.inputValueDefinitions.map { "~${it.name}" })
109+
110+
val argString = args.joinToString(sep)
111+
112+
signatures.add("${baseType.name}.${field.name}($argString)")
113+
if(isBoolean) {
114+
signatures.add("${baseType.name}.is${field.name.capitalize()}($argString)")
115+
}
116+
signatures.add("${baseType.name}.get${field.name.capitalize()}($argString)")
117+
if(scannedProperties) {
118+
signatures.add("${baseType.name}.${field.name}")
119+
}
120+
121+
return signatures
122+
}
123+
124+
data class Search(val type: Class<*>, val resolverInfo: ResolverInfo, val source: Any?, val requiredFirstParameterType: Class<*>? = null)
125+
}
126+
127+
class FieldResolverError(msg: String): RuntimeException(msg)

‎src/main/kotlin/com/coxautodev/graphql/tools/GenericType.kt‎

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ import java.util.concurrent.Future
1212
/**
1313
* @author Andrew Potter
1414
*/
15-
open class GenericType(protected val mostSpecificType: JavaType) {
15+
open internal class GenericType(protected val mostSpecificType: JavaType) {
1616

1717
fun isTypeAssignableFromRawClass(type: ParameterizedType, clazz: Class<*>): Boolean {
1818
return clazz.isAssignableFrom(getRawClass(type.rawType))
@@ -28,8 +28,19 @@ open class GenericType(protected val mostSpecificType: JavaType) {
2828
return TypeUtils.isAssignable(type, mostSpecificType)
2929
}
3030

31-
fun relativeTo(declaringClass: Class<*>) = relativeTo(getGenericSuperType(mostSpecificType, declaringClass) ?: error("Unable to find declaring type from class '${declaringClass.name}' relative to ${TypeUtils.toString(mostSpecificType)}"))
32-
fun relativeTo(declaringType: JavaType) = RelativeTo(declaringType, mostSpecificType)
31+
fun relativeToPotentialParent(declaringType: JavaType): RelativeTo {
32+
if(declaringType !is Class<*>) {
33+
return relativeToType(declaringType)
34+
}
35+
36+
val type = getGenericSuperType(mostSpecificType, declaringType)
37+
if(type == null) {
38+
error("Unable to find generic type of class ${TypeUtils.toString(declaringType)} relative to ${TypeUtils.toString(mostSpecificType)}")
39+
} else {
40+
return relativeToType(type)
41+
}
42+
}
43+
fun relativeToType(declaringType: JavaType) = RelativeTo(declaringType, mostSpecificType)
3344

3445
fun getGenericInterface(targetInterface: Class<*>) = getGenericInterface(mostSpecificType, targetInterface)
3546

@@ -69,7 +80,7 @@ open class GenericType(protected val mostSpecificType: JavaType) {
6980
return getGenericSuperType(raw.genericSuperclass, targetSuperClass)
7081
}
7182

72-
class RelativeTo constructor(private val declaringType: JavaType, mostSpecificType: JavaType): GenericType(mostSpecificType) {
83+
class RelativeTo (private val declaringType: JavaType, mostSpecificType: JavaType): GenericType(mostSpecificType) {
7384

7485
/**
7586
* Unwrap certain Java types to find the "real" class.

‎src/main/kotlin/com/coxautodev/graphql/tools/GraphQLMutationResolver.java‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,5 @@
33
/**
44
* @author Andrew Potter
55
*/
6-
public interface GraphQLMutationResolver extends GraphQLRootResolver {
7-
@Override
8-
default String getResolverName() {
9-
return RootTypeInfo.DEFAULT_MUTATION_NAME;
10-
}
6+
public interface GraphQLMutationResolver extends GraphQLResolver<Void> {
117
}

‎src/main/kotlin/com/coxautodev/graphql/tools/GraphQLQueryResolver.java‎

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,9 +3,5 @@
33
/**
44
* @author Andrew Potter
55
*/
6-
public interface GraphQLQueryResolver extends GraphQLRootResolver {
7-
@Override
8-
default String getResolverName() {
9-
return RootTypeInfo.DEFAULT_QUERY_NAME;
10-
}
6+
public interface GraphQLQueryResolver extends GraphQLResolver<Void> {
117
}

‎src/main/kotlin/com/coxautodev/graphql/tools/GraphQLRootResolver.java‎

Lines changed: 0 additions & 10 deletions
This file was deleted.
Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,4 @@
11
package com.coxautodev.graphql.tools;
22

3-
public interface GraphQLSubscriptionResolver extends GraphQLRootResolver {
4-
@Override
5-
default String getResolverName() {
6-
return RootTypeInfo.DEFAULT_SUBSCRIPTION_NAME;
7-
}
3+
public interface GraphQLSubscriptionResolver extends GraphQLResolver<Void> {
84
}
Lines changed: 116 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,116 @@
1+
package com.coxautodev.graphql.tools
2+
3+
import com.esotericsoftware.reflectasm.MethodAccess
4+
import com.fasterxml.jackson.core.type.TypeReference
5+
import com.fasterxml.jackson.databind.ObjectMapper
6+
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module
7+
import com.fasterxml.jackson.module.kotlin.registerKotlinModule
8+
import graphql.language.FieldDefinition
9+
import graphql.language.NonNullType
10+
import graphql.schema.DataFetcher
11+
import graphql.schema.DataFetchingEnvironment
12+
import java.lang.reflect.Method
13+
import java.util.Optional
14+
15+
/**
16+
* @author Andrew Potter
17+
*/
18+
internal class MethodFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, val method: Method): FieldResolver(field, search, method.declaringClass) {
19+
20+
val dataFetchingEnvironment = method.parameterCount == (field.inputValueDefinitions.size + getIndexOffset() + 1)
21+
22+
override fun createDataFetcher(): DataFetcher<*> {
23+
val args = mutableListOf<ArgumentPlaceholder>()
24+
25+
// Add source argument if this is a resolver (but not a root resolver)
26+
if(this.search.requiredFirstParameterType != null) {
27+
val expectedType = this.search.requiredFirstParameterType
28+
29+
args.add({ environment ->
30+
val source = environment.getSource<Any>()
31+
if (!(expectedType.isAssignableFrom(source.javaClass))) {
32+
throw ResolverError("Source type (${source.javaClass.name}) is not expected type (${expectedType.name})!")
33+
}
34+
35+
source
36+
})
37+
}
38+
39+
// Add an argument for each argument defined in the GraphQL schema
40+
this.field.inputValueDefinitions.forEachIndexed { index, definition ->
41+
42+
val genericParameterType = this.getJavaMethodParameterType(index) ?: throw ResolverError("Missing method type at position ${this.getJavaMethodParameterIndex(index)}, this is most likely a bug with graphql-java-tools")
43+
44+
val isNonNull = definition.type is NonNullType
45+
val isOptional = this.genericType.getRawClass(genericParameterType) == Optional::class.java
46+
47+
val typeReference = object: TypeReference<Any>() {
48+
override fun getType() = genericParameterType
49+
}
50+
51+
args.add({ environment ->
52+
val value = environment.arguments[definition.name] ?: if(isNonNull) {
53+
throw ResolverError("Missing required argument with name '${definition.name}', this is most likely a bug with graphql-java-tools")
54+
} else {
55+
null
56+
}
57+
58+
if(value == null && isOptional) {
59+
return@add Optional.empty<Any>()
60+
}
61+
62+
return@add MethodFieldResolverDataFetcher.mapper.convertValue(value, typeReference)
63+
})
64+
}
65+
66+
// Add DataFetchingEnvironment argument
67+
if(this.dataFetchingEnvironment) {
68+
args.add({ environment -> environment })
69+
}
70+
71+
return MethodFieldResolverDataFetcher(getSourceResolver(), this.method, args)
72+
}
73+
74+
override fun scanForMatches(): List<TypeClassMatcher.PotentialMatch> {
75+
val returnValueMatch = TypeClassMatcher.PotentialMatch.returnValue(field.type, method.genericReturnType, genericType, SchemaClassScanner.ReturnValueReference(method))
76+
77+
return field.inputValueDefinitions.mapIndexed { i, inputDefinition ->
78+
TypeClassMatcher.PotentialMatch.parameterType(inputDefinition.type, getJavaMethodParameterType(i)!!, genericType, SchemaClassScanner.MethodParameterReference(method, i))
79+
} + listOf(returnValueMatch)
80+
}
81+
82+
private fun getIndexOffset() = if(resolverInfo is NormalResolverInfo) 1 else 0
83+
fun getJavaMethodParameterIndex(index: Int) = index + getIndexOffset()
84+
85+
fun getJavaMethodParameterType(index: Int): JavaType? {
86+
val methodIndex = getJavaMethodParameterIndex(index)
87+
val parameters = method.parameterTypes
88+
if(parameters.size > methodIndex) {
89+
return method.genericParameterTypes[getJavaMethodParameterIndex(index)]
90+
} else {
91+
return null
92+
}
93+
}
94+
95+
override fun toString() = "MethodFieldResolver{method=$method}"
96+
}
97+
98+
class MethodFieldResolverDataFetcher(val sourceResolver: SourceResolver, method: Method, private val args: List<ArgumentPlaceholder>): DataFetcher<Any> {
99+
companion object {
100+
val mapper = ObjectMapper().registerModule(Jdk8Module()).registerKotlinModule()
101+
}
102+
103+
// Convert to reflactasm reflection
104+
private val methodAccess = MethodAccess.get(method.declaringClass)!!
105+
private val methodIndex = methodAccess.getIndex(method.name, *method.parameterTypes)
106+
107+
override fun get(environment: DataFetchingEnvironment): Any? {
108+
val source = sourceResolver(environment)
109+
val args = this.args.map { it(environment) }.toTypedArray()
110+
val result = methodAccess.invoke(source, methodIndex, *args)
111+
return if(result != null && result is Optional<*>) result.orElse(null) else result
112+
}
113+
}
114+
115+
internal typealias ArgumentPlaceholder = (DataFetchingEnvironment) -> Any?
116+
Lines changed: 27 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
package com.coxautodev.graphql.tools
2+
3+
import graphql.language.FieldDefinition
4+
import graphql.schema.DataFetcher
5+
import graphql.schema.DataFetchingEnvironment
6+
import java.lang.reflect.Field
7+
8+
/**
9+
* @author Andrew Potter
10+
*/
11+
internal class PropertyFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, val property: Field): FieldResolver(field, search, property.declaringClass) {
12+
override fun createDataFetcher(): DataFetcher<*> {
13+
return PropertyFieldResolverDataFetcher(getSourceResolver(), property)
14+
}
15+
16+
override fun scanForMatches(): List<TypeClassMatcher.PotentialMatch> {
17+
return listOf(TypeClassMatcher.PotentialMatch.returnValue(field.type, property.genericType, genericType, SchemaClassScanner.FieldTypeReference(property)))
18+
}
19+
20+
override fun toString() = "PropertyFieldResolver{property=$property}"
21+
}
22+
23+
class PropertyFieldResolverDataFetcher(private val sourceResolver: SourceResolver, private val field: Field): DataFetcher<Any> {
24+
override fun get(environment: DataFetchingEnvironment): Any {
25+
return field.get(sourceResolver(environment))
26+
}
27+
}

0 commit comments

Comments
 (0)