From d127e5e1570fd3709ef86cc1a8e43406e5cbc587 Mon Sep 17 00:00:00 2001 From: Danielle Voznyy Date: Sun, 11 Feb 2024 00:01:43 -0500 Subject: [PATCH] Allow skipping missing components in PolymorphicListAsMapSerializer --- .../PolymorphicListAsMapSerializer.kt | 35 +++++++++++++------ 1 file changed, 25 insertions(+), 10 deletions(-) diff --git a/addons/geary-serialization/src/commonMain/kotlin/com/mineinabyss/geary/serialization/serializers/PolymorphicListAsMapSerializer.kt b/addons/geary-serialization/src/commonMain/kotlin/com/mineinabyss/geary/serialization/serializers/PolymorphicListAsMapSerializer.kt index 62de00b0..2d047c5e 100644 --- a/addons/geary-serialization/src/commonMain/kotlin/com/mineinabyss/geary/serialization/serializers/PolymorphicListAsMapSerializer.kt +++ b/addons/geary-serialization/src/commonMain/kotlin/com/mineinabyss/geary/serialization/serializers/PolymorphicListAsMapSerializer.kt @@ -1,6 +1,7 @@ package com.mineinabyss.geary.serialization.serializers import com.mineinabyss.geary.datatypes.GearyComponent +import com.mineinabyss.geary.modules.geary import com.mineinabyss.geary.serialization.ComponentSerializers.Companion.fromCamelCaseToSnakeCase import com.mineinabyss.geary.serialization.ComponentSerializers.Companion.hasNamespace import com.mineinabyss.geary.serialization.ProvidedNamespaces @@ -20,6 +21,7 @@ open class PolymorphicListAsMapSerializer( ) : KSerializer> { // We need primary constructor to be a single serializer for generic serialization to work, use of() if manually creating private var prefix: String = "" + private var onMissingSerializer: OnMissing = OnMissing.WARN val polymorphicSerializer = serializer as? PolymorphicSerializer ?: error("Serializer is not polymorphic") @@ -44,13 +46,21 @@ open class PolymorphicListAsMapSerializer( } else -> { - components += compositeDecoder.decodeMapValue( - findSerializerFor( - compositeDecoder.serializersModule, - namespaces, - key - ) - ) + val componentSerializer = + runCatching { + findSerializerFor( + compositeDecoder.serializersModule, + namespaces, + key + ) + }.onFailure { + when (onMissingSerializer) { + OnMissing.ERROR -> throw it + OnMissing.WARN -> geary.logger.w("No serializer found for $key in namespaces $namespaces, ignoring") + OnMissing.IGNORE -> return@decode + } + }.getOrNull() ?: return + components += compositeDecoder.decodeMapValue(componentSerializer) } } } @@ -87,14 +97,19 @@ open class PolymorphicListAsMapSerializer( TODO("Not implemented") } + enum class OnMissing { + ERROR, WARN, IGNORE + } + companion object { fun of( serializer: PolymorphicSerializer, - prefix: String = "" - ): - PolymorphicListAsMapSerializer { + prefix: String = "", + onMissingSerializer: OnMissing = OnMissing.WARN, + ): PolymorphicListAsMapSerializer { return PolymorphicListAsMapSerializer(serializer).apply { this.prefix = prefix + this.onMissingSerializer = onMissingSerializer } }