julianpeeters / sbt-avrohugger

sbt plugin for generating Scala sources for Apache Avro schemas and protocols.
Apache License 2.0
133 stars 50 forks source link

question, define union of types #82

Open nicolaemarasoiu opened 4 years ago

nicolaemarasoiu commented 4 years ago

Hi, we have a Kafka topic with values of Avro type union of two Avro types (any message is of one or another type). When we have union types for fields, we know how to work with them in the Avro Hugger context, but when the union is top level, do you know a way to define an ad hoc type that is simply the union of the two explicit types? Thank you

nicolaemarasoiu commented 4 years ago

in an attempt to define a Serde for an Either type i realize that Avro spec must mention how to serde unions, do you know more details? thank you (i would imagine a header which indicates which particular type is instance by instance, so that both Serializer and Deserializer must first serde this type discriminator and then that type which is valid for that instance), so serializer below is not correct for sure even if it compiles)

implicit val consumed: Consumed[String, Either[TariffUpserted, TariffCancelled]] =
      Consumed.`with`(
        keySerde = Serdes.String,
        valueSerde = new Serde[Either[TariffUpserted, TariffCancelled]] {
          override def serializer(): Serializer[Either[TariffUpserted, TariffCancelled]] =
            (topic: String, data: Either[TariffUpserted, TariffCancelled]) => {
              data match {
                case Left(tariffUpserted) =>
                  implicitly[Serde[TariffUpserted]].serializer().serialize(topic, tariffUpserted)
                case Right(contractCancelled) =>
                  implicitly[Serde[TariffCancelled]]
                    .serializer()
                    .serialize(topic, contractCancelled)
              }
            }

          override def deserializer(): Deserializer[Either[TariffUpserted, TariffCancelled]] = {
            def deserializer(): Deserializer[Either[TariffUpserted, TariffCancelled]] =
              new Deserializer[Either[TariffUpserted, TariffCancelled]] {
                override def deserialize(
                    topic: String,
                    data: Array[Byte]
                ): Either[TariffUpserted, TariffCancelled] = {

                }
              }
          }
        }
      )