Skip to content

Commit

Permalink
Merge pull request #177 from avro-kotlin/main
Browse files Browse the repository at this point in the history
feat: Add support for decoding with avro aliases
  • Loading branch information
Chuckame authored Jan 27, 2024
2 parents 17eaf60 + 53a9b7e commit dc27771
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 0 deletions.
7 changes: 7 additions & 0 deletions src/main/kotlin/com/github/avrokotlin/avro4k/FieldNaming.kt
Original file line number Diff line number Diff line change
Expand Up @@ -21,4 +21,11 @@ class FieldNaming(private val name: String, annotations: List<Annotation>) {
* Takes into account @AvroName.
*/
fun name(): String = extractor.name() ?: name


/**
* Returns the avro aliases for the current element.
* Takes into account @AvroAlias.
*/
fun aliases(): List<String> = extractor.aliases()
}
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,13 @@ class RecordDecoder(
if (record.hasField(resolvedFieldName())) {
return record.get(resolvedFieldName())
}

FieldNaming(desc, currentIndex).aliases().forEach {
if (record.hasField(it)) {
return record.get(it)
}
}

return null
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
package com.github.avrokotlin.avro4k.decoder

import com.github.avrokotlin.avro4k.Avro
import com.github.avrokotlin.avro4k.AvroAlias
import io.kotest.core.spec.style.FunSpec
import io.kotest.matchers.shouldBe
import kotlinx.serialization.Serializable
import org.apache.avro.generic.GenericData

@Serializable
data class OldFooString(val s: String)
@Serializable
data class FooStringWithAlias(@AvroAlias("s") val str: String)

class AvroAliasTest : FunSpec({

test("decode with alias") {
val schema = Avro.default.schema(OldFooString.serializer())
val record = GenericData.Record(schema)
record.put("s", "hello")
Avro.default.fromRecord(FooStringWithAlias.serializer(), record) shouldBe FooStringWithAlias("hello")
}
})

0 comments on commit dc27771

Please sign in to comment.