SMILEY4 / schema-kenerator

Analyze kotlin types, extract information and generate schemas
Apache License 2.0
4 stars 0 forks source link

Include discriminator field for sealed classes #3

Open rChaoz opened 1 month ago

rChaoz commented 1 month ago

Note: This issue is about the kotlinx.serialization generator.

Description

Given the code:

@Serializable
sealed class Parent

@Serializable
data class ChildOne(val text: String)

@Serializable
data class ChildTwo(val number: Int)

val one = ChildOne("some_text")
val two = ChildTwo(123)

There is a difference between serializing one as Parent or as ChildOne:

The field name (here the default - type) can be changed by annotating the parent class with @JsonClassDiscriminator, and the values by annotating the child classes with @SerialName:


@Serializable
@JsonClassDiscriminator("the_type")
sealed class Parent

@Serializable
@SerialName("child_one")
data class ChildOne(val text: String)

@Serializable
@SerialName("child_two")
data class ChildTwo(val number: Int)

Then:

Issue

The generated schemas do not currently contain the type discriminator field.

Example

Given the data types:

@Serializable
sealed class Response

@Serializable
@SerialName("auth_failed")
data class AuthFailedResponse(
    val reason: String,
    val description: String,
    val scopes: String? = null
) : Response()

@Serializable
@SerialName("success")
data class SuccessfulResponse(val data: Data) : Response()

And the following config (schemas displayed using swagger-ui):

schemas {
    generator = { type ->
        type
            .processKotlinxSerialization()
            .connectSubTypes()
            .generateSwaggerSchema()
            .withAutoTitle(TitleType.SIMPLE)
            .compileReferencingRoot()
    }
}

Result:

image

Note

There doesn't seem to be any literal values support, so this would be tricky to fix.