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
Original file line number Diff line number Diff line change
Expand Up @@ -5,13 +5,18 @@ import com.esotericsoftware.reflectasm.MethodAccess
import com.fasterxml.jackson.core.type.TypeReference
import graphql.execution.batched.Batched
import graphql.language.FieldDefinition
import graphql.language.ListType
import graphql.language.NonNullType
import graphql.language.Type
import graphql.language.TypeName
import graphql.schema.DataFetcher
import graphql.schema.DataFetchingEnvironment
import graphql.schema.GraphQLTypeUtil.isScalar
import kotlinx.coroutines.GlobalScope
import kotlinx.coroutines.future.future
import java.lang.reflect.Method
import java.util.*
import java.util.Comparator
import java.util.Optional
import kotlin.coroutines.intrinsics.suspendCoroutineUninterceptedOrReturn
import kotlin.reflect.full.valueParameters
import kotlin.reflect.jvm.javaType
Expand Down Expand Up @@ -89,6 +94,12 @@ internal class MethodFieldResolver(field: FieldDefinition, search: FieldResolver
}
}

if (value != null
&& genericParameterType.unwrap().isAssignableFrom(value.javaClass)
&& isScalarType(environment, definition.type, genericParameterType)) {
return@add value
}

return@add mapper.convertValue(value, typeReference)
}
}
Expand All @@ -109,9 +120,24 @@ internal class MethodFieldResolver(field: FieldDefinition, search: FieldResolver
}
}

private fun isScalarType(environment: DataFetchingEnvironment, type: Type<*>, genericParameterType: JavaType): Boolean =
when (type) {
is ListType ->
List::class.java.isAssignableFrom(this.genericType.getRawClass(genericParameterType))
&& isScalarType(environment, type.type, this.genericType.unwrapGenericType(genericParameterType))
is TypeName ->
environment.graphQLSchema?.getType(type.name)?.let { isScalar(it) } ?: false
else ->
false
}

override fun scanForMatches(): List<TypeClassMatcher.PotentialMatch> {
val batched = isBatched(method, search)
val unwrappedGenericType = genericType.unwrapGenericType(try { method.kotlinFunction?.returnType?.javaType ?: method.genericReturnType } catch (e: InternalError) { method.genericReturnType })
val unwrappedGenericType = genericType.unwrapGenericType(try {
method.kotlinFunction?.returnType?.javaType ?: method.genericReturnType
} catch (e: InternalError) {
method.genericReturnType
})
val returnValueMatch = TypeClassMatcher.PotentialMatch.returnValue(field.type, unwrappedGenericType, genericType, SchemaClassScanner.ReturnValueReference(method), batched)

return field.inputValueDefinitions.mapIndexed { i, inputDefinition ->
Expand Down Expand Up @@ -148,7 +174,11 @@ open class MethodFieldResolverDataFetcher(private val sourceResolver: SourceReso
// Convert to reflactasm reflection
private val methodAccess = MethodAccess.get(method.declaringClass)!!
private val methodIndex = methodAccess.getIndex(method.name, *method.parameterTypes)
private val isSuspendFunction = try {method.kotlinFunction?.isSuspend == true } catch (e: InternalError) { false }
private val isSuspendFunction = try {
method.kotlinFunction?.isSuspend == true
} catch (e: InternalError) {
false
}

private class CompareGenericWrappers {
companion object : Comparator<GenericWrapper> {
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,112 @@
package com.coxautodev.graphql.tools

import graphql.ExecutionInput
import graphql.GraphQL
import graphql.language.StringValue
import graphql.schema.Coercing
import graphql.schema.GraphQLScalarType
import org.junit.Assert
import org.junit.Test

class MethodFieldResolverTest {

@Test
fun `should handle scalar types as method input argument`() {
val schema = SchemaParser.newParser()
.schemaString("""
scalar CustomScalar
type Query {
test(input: CustomScalar): Int
}
""".trimIndent()
)
.scalars(customScalarType)
.resolvers(object : GraphQLQueryResolver {
fun test(scalar: CustomScalar) = scalar.value.length
})
.build()
.makeExecutableSchema()

val gql = GraphQL.newGraphQL(schema).build()

val result = gql
.execute(ExecutionInput.newExecutionInput()
.query("""
query Test(${"$"}input: CustomScalar) {
test(input: ${"$"}input)
}
""".trimIndent())
.variables(mapOf("input" to "FooBar"))
.context(Object())
.root(Object()))

Assert.assertEquals(6, result.getData<Map<String, Any>>()["test"])
}

@Test
fun `should handle lists of scalar types`() {
val schema = SchemaParser.newParser()
.schemaString("""
scalar CustomScalar
type Query {
test(input: [CustomScalar]): Int
}
""".trimIndent()
)
.scalars(customScalarType)
.resolvers(object : GraphQLQueryResolver {
fun test(scalars: List<CustomScalar>) = scalars.map { it.value.length }.sum()
})
.build()
.makeExecutableSchema()

val gql = GraphQL.newGraphQL(schema).build()

val result = gql
.execute(ExecutionInput.newExecutionInput()
.query("""
query Test(${"$"}input: [CustomScalar]) {
test(input: ${"$"}input)
}
""".trimIndent())
.variables(mapOf("input" to listOf("Foo", "Bar")))
.context(Object())
.root(Object()))

Assert.assertEquals(6, result.getData<Map<String, Any>>()["test"])
}

/**
* Custom Scalar Class type that doesn't work with Jackson serialization/deserialization
*/
class CustomScalar private constructor(private val internalValue: String) {
val value get() = internalValue

companion object {
fun of(input: Any?) = when (input) {
is String -> CustomScalar(input)
else -> null
}
}
}

private val customScalarType: GraphQLScalarType = GraphQLScalarType.newScalar()
.name("CustomScalar")
.description("customScalar")
.coercing(object : Coercing<CustomScalar, String> {

override fun parseValue(input: Any?) = CustomScalar.of(input)

override fun parseLiteral(input: Any?) = when (input) {
is StringValue -> CustomScalar.of(input.value)
else -> null
}

override fun serialize(dataFetcherResult: Any?) = when (dataFetcherResult) {
is CustomScalar -> dataFetcherResult.value
else -> null
}
})
.build()

}