Skip to content

Instantly share code, notes, and snippets.

@gvolpe
Created June 18, 2021 11:19
Show Gist options
  • Save gvolpe/e3b7957078581b51e5fe77e2199b5381 to your computer and use it in GitHub Desktop.
Save gvolpe/e3b7957078581b51e5fe77e2199b5381 to your computer and use it in GitHub Desktop.

Revisions

  1. gvolpe created this gist Jun 18, 2021.
    36 changes: 36 additions & 0 deletions avro-newts.scala
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,36 @@
    import com.sksamuel.avro4s.SchemaFor
    import com.sksamuel.avro4s.refined._
    import io.estatico.newtype.Coercible
    import io.chrisdavenport.fuuid.FUUID
    import java.util.UUID
    import scala.concurrent.duration.FiniteDuration
    import io.circe.{Json, JsonObject}
    import com.comcast.ip4s.Ipv4Address

    object avro extends SchemaForCoercible {
    final case class MapOf[K, V](key: K, value: V)

    // Avro only supports Map[String, V] so any other map should be encoded as an array
    implicit def _mapSchemaFor[K: SchemaFor: =!=[*, String], V: SchemaFor]: SchemaFor[Map[K, V]] =
    SchemaFor[List[MapOf[K, V]]].forType[Map[K, V]]

    implicit val _schemaForFuuid: SchemaFor[FUUID] =
    SchemaFor[UUID].forType[FUUID]

    implicit val _schemaForDuration: SchemaFor[FiniteDuration] =
    SchemaFor[String].forType[FiniteDuration]

    implicit val _schemaForJsonObject: SchemaFor[JsonObject] =
    SchemaFor[String].forType[JsonObject]

    implicit val _schemaForJson: SchemaFor[Json] =
    SchemaFor[String].forType[Json]

    implicit val _schemaForIpv4Address: SchemaFor[Ipv4Address] =
    SchemaFor[String].forType[Ipv4Address]
    }

    trait SchemaForCoercible {
    implicit def _schemaForCoercible[A: Coercible[B, *], B: SchemaFor]: SchemaFor[A] =
    SchemaFor[B].forType[A]
    }