Skip to content

Commit

Permalink
Allow skipping missing components in PolymorphicListAsMapSerializer
Browse files Browse the repository at this point in the history
  • Loading branch information
0ffz committed Feb 11, 2024
1 parent eb905c2 commit d127e5e
Showing 1 changed file with 25 additions and 10 deletions.
Original file line number Diff line number Diff line change
@@ -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
Expand All @@ -20,6 +21,7 @@ open class PolymorphicListAsMapSerializer<T : Any>(
) : KSerializer<List<T>> {
// 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<T> ?: error("Serializer is not polymorphic")
Expand All @@ -44,13 +46,21 @@ open class PolymorphicListAsMapSerializer<T : Any>(
}

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)
}
}
}
Expand Down Expand Up @@ -87,14 +97,19 @@ open class PolymorphicListAsMapSerializer<T : Any>(
TODO("Not implemented")
}

enum class OnMissing {
ERROR, WARN, IGNORE
}

companion object {
fun <T : Any> of(
serializer: PolymorphicSerializer<T>,
prefix: String = ""
):
PolymorphicListAsMapSerializer<T> {
prefix: String = "",
onMissingSerializer: OnMissing = OnMissing.WARN,
): PolymorphicListAsMapSerializer<T> {
return PolymorphicListAsMapSerializer(serializer).apply {
this.prefix = prefix
this.onMissingSerializer = onMissingSerializer
}
}

Expand Down

0 comments on commit d127e5e

Please sign in to comment.