wix/greyhound

Creating a new Serde with ZIO effect (using ZIO api)

ivan-brko opened this issue · 4 comments

Is there a way to create a Serde which works with effects?
For example, if I'm creating a Serde by serializing/deserializing case classes to json, deserialization could potentially fail and as far as I can see I cannot describe this deserialization with ZIO effect, but I would have to throw an exception in this case and catch that somewhere.

This is current inmap:
def inmap[B](f: A => B)(g: B => A): Serde[B]

And I'm asking is there a way to get something like this:
def inmap[B, R, E](f: A => ZIO[R, E, B])(g: B => ZIO[R, E, A]): Serde[B]

hey @ivan-brko ,
Serde has an apply method that accepts a Deserializer and a Serializer, both are traits that return an effect.
See:
https://github.com/wix/greyhound/blob/master/core/src/main/scala/com/wixpress/dst/greyhound/core/Serde.scala#L19

Thanks for the quick answer, I'll use that one

hey @ivan-brko

I am also facing a similar problem while deserializing the case class, could you please share a sample code of creating Serde. I need to deserializing string JSON to case class and serializing case class to bytes.

@sumeetpri I'm using Play Json, and this is what i have now:

class BasePlayJsonDeserializer[+A](implicit fmt: Format[A]) extends Deserializer[A] {

  override def deserialize(topic: Topic, headers: Headers, data: Chunk[Byte]): Task[A] =
    ZIO
      .fromEither(
        Json
          .fromJson[A](Json.parse(new String(data.toArray, StandardCharsets.UTF_8)))
          .asEither
      )
      .mapError(err => new RuntimeException(s"Error while performing deserialization $err"))
}

and

class BasePlayJsonSerializer[-A](implicit fmt: Format[A]) extends Serializer[A] {

  override def serialize(topic: String, value: A): Task[Chunk[Byte]] =
    Task.succeed(Chunk.fromArray(Json.toJson(value).toString.getBytes()))
}

However, this is still WIP so some things could be improved.