Created
February 28, 2023 16:37
-
-
Save soujiro32167/09364fdb12b34ac9b5b44e286aabcc4e to your computer and use it in GitHub Desktop.
When your avro needs a discriminator in the payload
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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