Skip to content

Instantly share code, notes, and snippets.

@soujiro32167
Created February 28, 2023 16:37
Show Gist options
  • Save soujiro32167/09364fdb12b34ac9b5b44e286aabcc4e to your computer and use it in GitHub Desktop.
Save soujiro32167/09364fdb12b34ac9b5b44e286aabcc4e to your computer and use it in GitHub Desktop.
When your avro needs a discriminator in the payload
import vulcan.{AvroError, Codec}
import vulcan.generic.*
import zio.{ZIO, ZIOAppDefault}
sealed trait Foo
object Foo {
case class A(a: Int, `type`: "A" = "A") extends Foo
case class B(b: String, `type`: "B" = "B") extends Foo
implicit def singletonString[T <: String: ValueOf]: Codec[T] =
Codec.enumeration(
valueOf[T],
"singleton",
List(valueOf[T]),
identity,
s => Option.when(s == valueOf[T])(s.asInstanceOf[T]).toRight(AvroError("nope"))
)
implicit val codec: Codec[Foo] = Codec.derive[Foo]
}
object go extends ZIOAppDefault {
override def run = {
for {
schema <- ZIO.fromEither(Foo.codec.schema).debug
_ <- ZIO.fromEither(Foo.codec.encode(Foo.A(1)).flatMap(a => Foo.codec.decode(a, schema))).debug
} yield ()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment