Netflix / dgs-codegen

Apache License 2.0
183 stars 99 forks source link

How can I use enum as a scalar type? #481

Closed woskaangel closed 2 years ago

woskaangel commented 2 years ago

SexType.kt

enum class SexType {
    M,
    W,
    N,
}

SexTypeScalar.kt

@DgsScalar(name = "SexType")
class SexTypeScalar : Coercing<SexType, SexType> {
    @Throws(CoercingSerializeException::class)
    override fun serialize(dataFetcherResult: Any): SexType {
        if (dataFetcherResult !is SexType) {
            throw CoercingSerializeException("Not a valid SexType")
        }
        return dataFetcherResult
    }

    @Throws(CoercingParseValueException::class)
    override fun parseValue(input: Any): SexType {
        return input as SexType
    }

    @Throws(CoercingParseLiteralException::class)
    override fun parseLiteral(input: Any): SexType {
        if (input !is SexType) {
            throw CoercingParseLiteralException("Value is not a valid SexType")
        }
        return input
    }
}

schema.graphqls

input SignUpInput {
    email: String
    name: String!
    birth: DateTime!,
    sex: SexType!
}

scalar DateTime
scalar SexType

generated code: SignUpInput.kt

package co.test.generated.types

import com.fasterxml.jackson.`annotation`.JsonProperty
import java.time.OffsetDateTime
import kotlin.String

public data class SignUpInput(
  @JsonProperty("email")
  public val email: String? = null,
  @JsonProperty("name")
  public val name: String,
  @JsonProperty("birth")
  public val birth: OffsetDateTime,
  @JsonProperty("sex")
  public val sex: SexType
) {
  public companion object
}

SexType has an error. 'Unresolved reference: SexType'. However, DateTime has no errors.

srinivasankavitha commented 2 years ago

This is expected behavior. Codegen needs to be told what type to map the scalar to. So you need to add a type mapping for for scalar to the enum class you are using to map it to: https://netflix.github.io/dgs/generating-code-from-schema/#mapping-existing-types

woskaangel commented 2 years ago

Thanks. I solved this problem.

I added this code to build.gradle.kts

@OptIn(kotlin.ExperimentalStdlibApi::class)
tasks.withType<com.netflix.graphql.dgs.codegen.gradle.GenerateJavaTask> {
    typeMapping = mutableMapOf(
        "SexType" to "co.test.enums.SexType",
        "SignConnectionType" to "co.test.enums.SignConnectionType"
    )
}