Razvan
10/10/2021, 10:01 PMprivate val type by obj(JTitleType, TitleRequest::type)
and a few tricks
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)
}
}