Skip to content

[client] update ScalarConverter to accept any objects #819

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Aug 26, 2020
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 @@ -22,12 +22,12 @@ package com.expediagroup.graphql.client.converter
interface ScalarConverter<T> {

/**
* Deserialize raw JSON String value to a typesafe value.
* Deserialize raw JSON value to a typesafe value.
*/
fun toScalar(rawValue: String): T
fun toScalar(rawValue: Any): T

/**
* Serialize typesafe scalar value to a raw JSON string.
* Serialize typesafe scalar value to a raw JSON value.
*/
fun toJson(value: T): String
fun toJson(value: T): Any
}
12 changes: 5 additions & 7 deletions docs/client/client-customization.md
Original file line number Diff line number Diff line change
Expand Up @@ -150,13 +150,13 @@ val customObjectMapper = jacksonObjectMapper()
val client = GraphQLClient(url = URL("http://localhost:8080/graphql"), mapper = customObjectMapper)
```

## Deprecated Field Usage
## Deprecated Field Usage

Build plugins will automatically fail generation of a client if any of the specified query files are referencing
deprecated fields. This ensures that your clients have to explicitly opt-in into deprecated usage by specifying
`allowDeprecatedFields` configuration option.

## Custom GraphQL Scalars
## Custom GraphQL Scalars

By default, custom GraphQL scalars are serialized and [type-aliased](https://kotlinlang.org/docs/reference/type-aliases.html)
to a String. GraphQL Kotlin plugins also support custom serialization based on provided configuration.
Expand All @@ -171,8 +171,8 @@ import com.expediagroup.graphql.client.converter.ScalarConverter
import java.util.UUID

class UUIDScalarConverter : ScalarConverter<UUID> {
override fun toScalar(rawValue: String): UUID = UUID.fromString(rawValue)
override fun toJson(value: UUID): String = value.toString()
override fun toScalar(rawValue: Any): UUID = UUID.fromString(rawValue.toString())
override fun toJson(value: UUID): Any = value.toString()
}
```

Expand All @@ -189,6 +189,4 @@ graphql {
}
```

See [Gradle](../plugins/gradle-plugin.md)
and [Maven](../plugins/maven-plugin.md)
plugin documentation for additional details.
See [Gradle](../plugins/gradle-plugin.md) and [Maven](../plugins/maven-plugin.md) plugin documentation for additional details.
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,17 @@ package com.expediagroup.graphql.examples.hooks

import com.expediagroup.graphql.directives.KotlinDirectiveWiringFactory
import com.expediagroup.graphql.hooks.SchemaGeneratorHooks
import graphql.Scalars
import graphql.language.StringValue
import graphql.schema.Coercing
import graphql.schema.CoercingParseLiteralException
import graphql.schema.CoercingParseValueException
import graphql.schema.CoercingSerializeException
import graphql.schema.GraphQLScalarType
import graphql.schema.GraphQLType
import org.springframework.beans.factory.BeanFactoryAware
import reactor.core.publisher.Mono
import java.math.BigDecimal
import java.util.UUID
import kotlin.reflect.KClass
import kotlin.reflect.KType
Expand All @@ -39,6 +44,7 @@ class CustomSchemaGeneratorHooks(override val wiringFactory: KotlinDirectiveWiri
*/
override fun willGenerateGraphQLType(type: KType): GraphQLType? = when (type.classifier) {
UUID::class -> graphqlUUIDType
BigDecimal::class -> Scalars.GraphQLBigDecimal
else -> null
}

Expand Down Expand Up @@ -68,16 +74,24 @@ internal val graphqlUUIDType = GraphQLScalarType.newScalar()
.build()

private object UUIDCoercing : Coercing<UUID, String> {
override fun parseValue(input: Any?): UUID = UUID.fromString(
serialize(
input
)
)
override fun parseValue(input: Any): UUID = runCatching {
UUID.fromString(serialize(input))
}.getOrElse {
throw CoercingParseValueException("Expected valid UUID but was $input")
}

override fun parseLiteral(input: Any?): UUID? {
override fun parseLiteral(input: Any): UUID? {
val uuidString = (input as? StringValue)?.value
return UUID.fromString(uuidString)
return runCatching {
UUID.fromString(uuidString)
}.getOrElse {
throw CoercingParseLiteralException("Expected valid UUID literal but was $uuidString")
}
}

override fun serialize(dataFetcherResult: Any?): String = dataFetcherResult.toString()
override fun serialize(dataFetcherResult: Any): String = runCatching {
dataFetcherResult.toString()
}.getOrElse {
throw CoercingSerializeException("Data fetcher result $dataFetcherResult cannot be serialized to a String")
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ import com.expediagroup.graphql.spring.operations.Mutation
import com.expediagroup.graphql.spring.operations.Query
import com.expediagroup.graphql.scalars.ID
import org.springframework.stereotype.Component
import java.math.BigDecimal
import java.util.UUID
import kotlin.random.Random

/**
* Simple query that exposes custom scalar.
Expand All @@ -39,6 +41,9 @@ class ScalarQuery : Query {

@GraphQLDescription("generates random GraphQL ID")
fun generateRandomId() = ID(UUID.randomUUID().toString())

@GraphQLDescription("generates random BigDecimal")
fun generateRandomBigDecimal(): BigDecimal = BigDecimal(Random.nextLong())
}

@Component
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import com.expediagroup.graphql.client.converter.ScalarConverter
import java.util.UUID

class UUIDScalarConverter : ScalarConverter<UUID> {
override fun toScalar(rawValue: String): UUID = UUID.fromString(rawValue)
override fun toJson(value: UUID): String = value.toString()
override fun toScalar(rawValue: Any): UUID = UUID.fromString(rawValue.toString())
override fun toJson(value: UUID): Any = value.toString()
}
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,6 @@ import com.expediagroup.graphql.client.converter.ScalarConverter
import java.util.UUID

class UUIDScalarConverter : ScalarConverter<UUID> {
override fun toScalar(rawValue: String): UUID = UUID.fromString(rawValue)
override fun toJson(value: UUID): String = value.toString()
override fun toScalar(rawValue: Any): UUID = UUID.fromString(rawValue.toString())
override fun toJson(value: UUID): Any = value.toString()
}
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,7 @@ internal fun generateGraphQLCustomScalarTypeSpec(context: GraphQLClientGenerator
FunSpec.builder("create")
.addAnnotation(JsonCreator::class.java)
.jvmStatic()
.addParameter("rawValue", String::class)
.addParameter("rawValue", Any::class)
.addStatement("return %L(%N.toScalar(rawValue))", customScalarName, converter)
.build()
)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ class GenerateGraphQLCustomScalarTypeSpecIT {
import com.expediagroup.graphql.types.GraphQLResponse
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonValue
import kotlin.Any
import kotlin.String
import kotlin.jvm.JvmStatic

Expand All @@ -61,7 +62,7 @@ class GenerateGraphQLCustomScalarTypeSpecIT {

@JsonCreator
@JvmStatic
fun create(rawValue: String) = UUID(converter.toScalar(rawValue))
fun create(rawValue: Any) = UUID(converter.toScalar(rawValue))
}
}

Expand Down