commonMain.inkapplications.shade.events.CompositeEventDeserializer.kt Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of events-js Show documentation
Show all versions of events-js Show documentation
Multiplatform Kotlin SDK for Hue lighting controls (unofficial)
package inkapplications.shade.events
import inkapplications.shade.structures.UndocumentedApi
import inkapplications.shade.structures.UnknownEvent
import kimchi.logger.KimchiLogger
import kotlinx.serialization.DeserializationStrategy
import kotlinx.serialization.descriptors.SerialDescriptor
import kotlinx.serialization.encoding.Decoder
import kotlinx.serialization.json.*
/**
* Deserializes events by delegating to a serializer registered by type.
*/
@OptIn(UndocumentedApi::class)
internal class CompositeEventDeserializer(
private val json: Json,
private val logger: KimchiLogger,
): DeserializationStrategy>, EventSerializerContainer {
private val serializers = mutableMapOf>()
private val backingSerializer = JsonElement.serializer()
override val descriptor: SerialDescriptor get() = backingSerializer.descriptor
override fun deserialize(decoder: Decoder): List {
return backingSerializer.deserialize(decoder)
.jsonArray
.flatMap { it.jsonObject["data"]?.jsonArray?.toList().orEmpty() }
.map { data ->
data.jsonObject["type"]
?.jsonPrimitive
?.contentOrNull
?.let { serializers[it] }
?.let {
runCatching { json.decodeFromJsonElement(it, data) }
.onFailure { logger.error("Event Deserialization Failed", it) }
.getOrNull()
}
?: UnknownEvent(
type = data.jsonObject["type"]?.jsonPrimitive?.contentOrNull ?: throw IllegalArgumentException("Data without type"),
json = data.toString(),
)
}
}
override fun setDeserializer(type: String, deserializer: DeserializationStrategy) {
serializers[type] = deserializer
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy