Created
October 15, 2021 16:59
-
-
Save razvn/7521ed170dcd38ecf881b708adca8674 to your computer and use it in GitHub Desktop.
Kondor-Enum_label_serialisation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package net.razvan.kondortest | |
import net.razvan.kondortest.TitleType.Companion.fromLabel | |
import com.ubertob.kondor.json.JAny | |
import com.ubertob.kondor.json.JStringRepresentable | |
import com.ubertob.kondor.json.jsonnode.JsonNodeObject | |
import com.ubertob.kondor.json.obj | |
import com.ubertob.kondor.json.str | |
import com.ubertob.kondor.json.toPrettyJson | |
import com.ubertob.kondor.outcome.recover | |
import io.kotest.matchers.shouldBe | |
import org.junit.jupiter.api.Test | |
data class TitleRequest( | |
val id: String, | |
val type: TitleType? | |
) | |
enum class TitleType(val label: String) { | |
Movie("movie"), Series("series"), Episoode("episode"); | |
companion object { | |
fun fromLabel(label: String) = values().first { it.label == label } | |
} | |
} | |
object JTitleType : JStringRepresentable<TitleType>() { | |
override val cons: (String) -> TitleType = ::fromLabel | |
override val render: (TitleType) -> String = TitleType::label | |
} | |
object JTitleRequest : JAny<TitleRequest>() { | |
private val id by str(TitleRequest::id) | |
private val type by obj(JTitleType, TitleRequest::type) | |
override fun JsonNodeObject.deserializeOrThrow(): TitleRequest = | |
TitleRequest( | |
id = +id, | |
type = type.getter(this).recover { null } | |
) | |
} | |
class KondorTest { | |
@Test | |
fun `type not null`() { | |
val inValue = TitleRequest("tom", TitleType.Movie) | |
val json = JTitleRequest.toPrettyJson(inValue).also { | |
println(it) | |
} | |
json shouldBe """ | |
{ | |
"id": "tom", | |
"type": "movie" | |
} | |
""".trimIndent() | |
} | |
@Test | |
fun `type is null`() { | |
val inValue = TitleRequest("tom", null) | |
val json = JTitleRequest.toPrettyJson(inValue).also { | |
println(it) | |
} | |
json shouldBe """ | |
{ | |
"id": "tom" | |
} | |
""".trimIndent() | |
} | |
@Test | |
fun `type is set to null when type is unknown`() { | |
val inValue = """ | |
{ | |
"id": "tom", | |
"type": "unknown" | |
} | |
""".trimIndent() | |
val title = JTitleRequest.fromJson(inValue).orThrow() | |
title shouldBe TitleRequest("tom", null) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment