aPureBase / KGraphQL

Pure Kotlin GraphQL implementation
https://kgraphql.io
MIT License
298 stars 58 forks source link

MongoDb ObjectId in serialized data class error " An Object type must define one or more fields. Found none on type Id" #181

Open ronjunevaldoz opened 2 years ago

ronjunevaldoz commented 2 years ago

Having an error com.apurebase.kgraphql.schema.SchemaException: An Object type must define one or more fields. Found none on type Id

Mongo User Document Model

@Serializable
data class User(
    @SerialName("_id")
    @Contextual val id: Id<User> = newId(),
    val username: String,
    val password: String,
)

Schema Type

type<Id<User>>()
type<User>()
PssbleTrngle commented 1 year ago

Should the ObjectId of a model not rather be defined in graphql using a scalar and mapping it to a string?

poovarasanvasudevan commented 1 year ago

Solved with

schema {
        configure {
            genericTypeResolver = object: DefaultGenericTypeResolver() {
                override fun resolveMonad(type: KType): KType = when {
                    type.jvmErasure.isSubclassOf(Id::class) -> type.arguments[0].type!!.withNullability(type.isMarkedNullable)
                    else -> super.resolveMonad(type)
                }

                override fun unbox(obj: Any): Any? = when(obj) {
                    is Id<*> -> obj.toString()
                    else -> super.unbox(obj)
                }
            }
        }
}