Skip to content

Commit 8ce5375

Browse files
committed
Allow modification of generic 'wrapper' types (fixes graphql-java-kickstart#47) and begin support for partial schemas (graphql-java-kickstart#39)
1 parent 72e6389 commit 8ce5375

15 files changed

Lines changed: 176 additions & 50 deletions

File tree

‎example/src/main/java/com/coxautodev/graphql/tools/example/CharacterRepository.java‎

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,6 @@
11
package com.coxautodev.graphql.tools.example;
22

3-
import com.coxautodev.graphql.tools.example.types.Character;
43
import com.coxautodev.graphql.tools.example.types.Droid;
5-
import com.coxautodev.graphql.tools.example.types.Episode;
6-
import com.coxautodev.graphql.tools.example.types.Human;
74
import org.springframework.stereotype.Component;
85

96
import java.util.Arrays;

‎example/src/main/java/com/coxautodev/graphql/tools/example/resolvers/Query.java‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@
77
import com.coxautodev.graphql.tools.example.types.Droid;
88
import com.coxautodev.graphql.tools.example.types.Episode;
99
import com.coxautodev.graphql.tools.example.types.Human;
10+
import graphql.schema.DataFetchingEnvironment;
1011
import org.springframework.beans.factory.annotation.Autowired;
1112
import org.springframework.stereotype.Component;
1213

@@ -20,7 +21,7 @@ public Character hero(Episode episode) {
2021
return episode != null ? characterRepository.getHeroes().get(episode) : characterRepository.getCharacters().get("1000");
2122
}
2223

23-
public Human human(String id) {
24+
public Human human(String id, DataFetchingEnvironment env) {
2425
return (Human) characterRepository.getCharacters().values().stream()
2526
.filter(character -> character instanceof Human && character.getId().equals(id))
2627
.findFirst()

‎example/src/main/resources/swapi.graphqls‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,10 @@ type Query {
55
character(id: String!): Character @doc(d: "Find character by id")
66
}
77

8+
type Mutation {
9+
10+
}
11+
812
enum Episode @doc(d: "One of the films in the Star Wars Trilogy") {
913
NEWHOPE @doc(d: "Released in 1977"),
1014
EMPIRE @doc(d: "Released in 1980"),

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

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,9 @@ import graphql.schema.DataFetchingEnvironment
77
/**
88
* @author Andrew Potter
99
*/
10-
internal abstract class FieldResolver(val field: FieldDefinition, val search: FieldResolverScanner.Search, relativeTo: JavaType) {
10+
internal abstract class FieldResolver(val field: FieldDefinition, val search: FieldResolverScanner.Search, relativeTo: JavaType, options: SchemaParserOptions) {
1111
val resolverInfo: ResolverInfo = search.resolverInfo
12-
val genericType = GenericType(search.type).relativeToPotentialParent(relativeTo)
12+
val genericType = GenericType(search.type, options).relativeToPotentialParent(relativeTo)
1313

1414
abstract fun scanForMatches(): List<TypeClassMatcher.PotentialMatch>
1515
abstract fun createDataFetcher(): DataFetcher<*>
@@ -32,4 +32,9 @@ internal abstract class FieldResolver(val field: FieldDefinition, val search: Fi
3232
}
3333
}
3434

35+
internal class MissingFieldResolver(field: FieldDefinition, options: SchemaParserOptions): FieldResolver(field, FieldResolverScanner.Search(Any::class.java, MissingResolverInfo(), null), Any::class.java, options) {
36+
override fun scanForMatches(): List<TypeClassMatcher.PotentialMatch> = listOf()
37+
override fun createDataFetcher(): DataFetcher<*> = DataFetcher<Any> { TODO("Schema resolver not implemented") }
38+
}
39+
3540
internal typealias SourceResolver = (DataFetchingEnvironment) -> Any

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

Lines changed: 19 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -6,17 +6,21 @@ import graphql.language.TypeName
66
import graphql.schema.DataFetchingEnvironment
77
import org.apache.commons.lang3.ClassUtils
88
import org.apache.commons.lang3.reflect.FieldUtils
9+
import org.slf4j.LoggerFactory
910
import java.lang.reflect.Field
1011
import java.lang.reflect.Method
12+
import java.lang.reflect.Modifier
1113

1214
/**
1315
* @author Andrew Potter
1416
*/
15-
internal class FieldResolverScanner {
17+
internal class FieldResolverScanner(val options: SchemaParserOptions) {
1618

1719
companion object {
20+
private val log = LoggerFactory.getLogger(FieldResolverScanner::class.java)
21+
1822
fun getAllMethods(type: Class<*>): List<Method> {
19-
return type.declaredMethods.toList() + ClassUtils.getAllSuperclasses(type).flatMap { it.declaredMethods.toList() }
23+
return type.declaredMethods.toList() + ClassUtils.getAllSuperclasses(type).flatMap { it.declaredMethods.toList() }.filter { !Modifier.isPrivate(it.modifiers) }
2024
}
2125
}
2226

@@ -30,19 +34,29 @@ internal class FieldResolverScanner {
3034
throw FieldResolverError("Found more than one matching resolver for field '$field': $found")
3135
}
3236

33-
return found.firstOrNull() ?: throw FieldResolverError(getMissingFieldMessage(field, searches, scanProperties))
37+
return found.firstOrNull() ?: missingFieldResolver(field, searches, scanProperties)
38+
}
39+
40+
fun missingFieldResolver(field: FieldDefinition, searches: List<Search>, scanProperties: Boolean): FieldResolver {
41+
return if(options.allowUnimplementedResolvers) {
42+
log.warn("Missing resolver for field: $field")
43+
44+
MissingFieldResolver(field, options)
45+
} else {
46+
throw FieldResolverError(getMissingFieldMessage(field, searches, scanProperties))
47+
}
3448
}
3549

3650
private fun findFieldResolver(field: FieldDefinition, search: Search, scanProperties: Boolean): FieldResolver? {
3751
val method = findResolverMethod(field, search)
3852
if(method != null) {
39-
return MethodFieldResolver(field, search, method.apply { isAccessible = true })
53+
return MethodFieldResolver(field, search, options, method.apply { isAccessible = true })
4054
}
4155

4256
if(scanProperties) {
4357
val property = findResolverProperty(field, search)
4458
if(property != null) {
45-
return PropertyFieldResolver(field, search, property.apply { isAccessible = true })
59+
return PropertyFieldResolver(field, search, options, property.apply { isAccessible = true })
4660
}
4761
}
4862

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

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,14 +5,11 @@ import org.apache.commons.lang3.reflect.TypeUtils
55
import sun.reflect.generics.reflectiveObjects.WildcardTypeImpl
66
import java.lang.reflect.ParameterizedType
77
import java.lang.reflect.TypeVariable
8-
import java.util.concurrent.CompletableFuture
9-
import java.util.concurrent.CompletionStage
10-
import java.util.concurrent.Future
118

129
/**
1310
* @author Andrew Potter
1411
*/
15-
open internal class GenericType(protected val mostSpecificType: JavaType) {
12+
open internal class GenericType(protected val mostSpecificType: JavaType, protected val options: SchemaParserOptions) {
1613

1714
fun isTypeAssignableFromRawClass(type: ParameterizedType, clazz: Class<*>): Boolean {
1815
return clazz.isAssignableFrom(getRawClass(type.rawType))
@@ -40,7 +37,7 @@ open internal class GenericType(protected val mostSpecificType: JavaType) {
4037
return relativeToType(type)
4138
}
4239
}
43-
fun relativeToType(declaringType: JavaType) = RelativeTo(declaringType, mostSpecificType)
40+
fun relativeToType(declaringType: JavaType) = RelativeTo(declaringType, mostSpecificType, options)
4441

4542
fun getGenericInterface(targetInterface: Class<*>) = getGenericInterface(mostSpecificType, targetInterface)
4643

@@ -80,20 +77,23 @@ open internal class GenericType(protected val mostSpecificType: JavaType) {
8077
return getGenericSuperType(raw.genericSuperclass, targetSuperClass)
8178
}
8279

83-
class RelativeTo (private val declaringType: JavaType, mostSpecificType: JavaType): GenericType(mostSpecificType) {
80+
class RelativeTo(private val declaringType: JavaType, mostSpecificType: JavaType, options: SchemaParserOptions): GenericType(mostSpecificType, options) {
8481

8582
/**
8683
* Unwrap certain Java types to find the "real" class.
8784
*/
8885
fun unwrapGenericType(type: JavaType): JavaType {
8986
return when(type) {
9087
is ParameterizedType -> {
91-
return when(type.rawType) {
92-
Future::class.java -> unwrapGenericType(type.actualTypeArguments.first())
93-
CompletionStage::class.java -> unwrapGenericType(type.actualTypeArguments.first())
94-
CompletableFuture::class.java -> unwrapGenericType(type.actualTypeArguments.first())
95-
else -> type
88+
val rawType = type.rawType
89+
val genericType = options.genericWrappers.find { it.type == rawType } ?: return type
90+
91+
val typeArguments = type.actualTypeArguments
92+
if(typeArguments.size <= genericType.index) {
93+
throw IndexOutOfBoundsException("Generic type '${TypeUtils.toString(type)}' does not have a type argument at index ${genericType.index}!")
9694
}
95+
96+
return unwrapGenericType(typeArguments[genericType.index])
9797
}
9898
is Class<*> -> if(type.isPrimitive) Primitives.wrap(type) else type
9999
is TypeVariable<*> -> {

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import java.util.Optional
1515
/**
1616
* @author Andrew Potter
1717
*/
18-
internal class MethodFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, val method: Method): FieldResolver(field, search, method.declaringClass) {
18+
internal class MethodFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, options: SchemaParserOptions, val method: Method): FieldResolver(field, search, method.declaringClass, options) {
1919

2020
val dataFetchingEnvironment = method.parameterCount == (field.inputValueDefinitions.size + getIndexOffset() + 1)
2121

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

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ import java.lang.reflect.Field
88
/**
99
* @author Andrew Potter
1010
*/
11-
internal class PropertyFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, val property: Field): FieldResolver(field, search, property.declaringClass) {
11+
internal class PropertyFieldResolver(field: FieldDefinition, search: FieldResolverScanner.Search, options: SchemaParserOptions, val property: Field): FieldResolver(field, search, property.declaringClass, options) {
1212
override fun createDataFetcher(): DataFetcher<*> {
1313
return PropertyFieldResolverDataFetcher(getSourceResolver(), property)
1414
}

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

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,13 +7,13 @@ internal abstract class ResolverInfo {
77
abstract fun getFieldSearches(): List<FieldResolverScanner.Search>
88
}
99

10-
internal class NormalResolverInfo(val resolver: GraphQLResolver<*>): ResolverInfo() {
10+
internal class NormalResolverInfo(val resolver: GraphQLResolver<*>, private val options: SchemaParserOptions): ResolverInfo() {
1111
val resolverType = resolver.javaClass
1212
val dataClassType = findDataClass()
1313

1414
private fun findDataClass(): Class<*> {
1515
// Grab the parent interface with type GraphQLResolver from our resolver and get its first type argument.
16-
val interfaceType = GenericType(resolverType).getGenericInterface(GraphQLResolver::class.java)
16+
val interfaceType = GenericType(resolverType, options).getGenericInterface(GraphQLResolver::class.java)
1717
if(interfaceType == null || interfaceType !is ParameterizedType) {
1818
error("${GraphQLResolver::class.java.simpleName} interface was not parameterized for: ${resolverType.name}")
1919
}
@@ -51,4 +51,8 @@ internal class DataClassResolverInfo(val dataClass: Class<*>): ResolverInfo() {
5151
}
5252
}
5353

54+
internal class MissingResolverInfo: ResolverInfo() {
55+
override fun getFieldSearches(): List<FieldResolverScanner.Search> = listOf()
56+
}
57+
5458
class ResolverError(message: String, cause: Throwable? = null) : RuntimeException(message, cause)

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

Lines changed: 8 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ import java.lang.reflect.Method
2323
/**
2424
* @author Andrew Potter
2525
*/
26-
internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, allDefinitions: List<Definition>, resolvers: List<GraphQLResolver<*>>, private val scalars: CustomScalarMap) {
26+
internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, allDefinitions: List<Definition>, resolvers: List<GraphQLResolver<*>>, private val scalars: CustomScalarMap, private val options: SchemaParserOptions) {
2727

2828
companion object {
2929
val log = LoggerFactory.getLogger(SchemaClassScanner::class.java)!!
@@ -35,7 +35,7 @@ internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, al
3535
private val mutationResolvers = resolvers.filterIsInstance<GraphQLMutationResolver>()
3636
private val subscriptionResolvers = resolvers.filterIsInstance<GraphQLSubscriptionResolver>()
3737

38-
private val resolverInfos = resolvers.minus(queryResolvers).minus(mutationResolvers).minus(subscriptionResolvers).map { NormalResolverInfo(it) }
38+
private val resolverInfos = resolvers.minus(queryResolvers).minus(mutationResolvers).minus(subscriptionResolvers).map { NormalResolverInfo(it, options) }
3939
private val resolverInfosByDataClass = this.resolverInfos.associateBy { it.dataClassType }
4040

4141
private val initialDictionary = initialDictionary.mapValues { InitialDictionaryEntry(it.value) }
@@ -46,7 +46,7 @@ internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, al
4646
private val objectDefinitionsByName = objectDefinitions.associateBy { it.name }
4747
private val interfaceDefinitionsByName = allDefinitions.filterIsInstance<InterfaceTypeDefinition>().associateBy { it.name }
4848

49-
private val fieldResolverScanner = FieldResolverScanner()
49+
private val fieldResolverScanner = FieldResolverScanner(options)
5050
private val typeClassMatcher = TypeClassMatcher(definitionsByName)
5151
private val dictionary = mutableMapOf<TypeDefinition, DictionaryEntry>()
5252
private val unvalidatedTypes = mutableSetOf<TypeDefinition>()
@@ -60,6 +60,10 @@ internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, al
6060
throw SchemaClassScannerError("Class in supplied dictionary '${clazz.name}' specified type name '$name', but a type definition with that name was not found!")
6161
}
6262
}
63+
64+
if(options.allowUnimplementedResolvers) {
65+
log.warn("Option 'allowUnimplementedResolvers' should only be set to true during development, as it can cause schema errors to be moved to query time instead of schema creation time. Make sure this is turned off in production.")
66+
}
6367
}
6468

6569
/**
@@ -250,7 +254,7 @@ internal class SchemaClassScanner(initialDictionary: BiMap<String, Class<*>>, al
250254
findInputValueType(inputValueDefinition.name, javaType)?.let { inputValueJavaType ->
251255
val inputGraphQLType = inputValueDefinition.type.unwrap()
252256
if(inputGraphQLType is TypeName && !ScalarInfo.STANDARD_SCALAR_DEFINITIONS.containsKey(inputGraphQLType.name)) {
253-
handleFoundType(typeClassMatcher.match(TypeClassMatcher.PotentialMatch.parameterType(inputValueDefinition.type, inputValueJavaType, GenericType(javaType).relativeToType(inputValueJavaType), InputObjectReference(inputValueDefinition))))
257+
handleFoundType(typeClassMatcher.match(TypeClassMatcher.PotentialMatch.parameterType(inputValueDefinition.type, inputValueJavaType, GenericType(javaType, options).relativeToType(inputValueJavaType), InputObjectReference(inputValueDefinition))))
254258
}
255259
}
256260
}

0 commit comments

Comments
 (0)