Integrating Zio-Kafka Consumers with Zio-Json deserializer

418 views Asked by At

I'm studying the library zio-kafka, and I want to use zio-json to deserialize messages' values in JSON format.

I have a simple case class together with its decoder and encoder:

case class Player(name: String, score: Int)
object Player {
  implicit val decoder: JsonDecoder[Player] = DeriveJsonDecoder.gen[Player]
  implicit val encoder: JsonEncoder[Player] = DeriveJsonEncoder.gen[Player]
}

Right now, I created a Serde starting from a Serde.string that uses the above decoder / encoder:

val playerSerde: Serde[Any, Player] = Serde.string.inmapM { playerAsString =>
  ZIO.fromEither(playerAsString.fromJson[Player].left.map(new RuntimeException(_)))
} { playerAsObj =>
  ZIO.effect(playerAsObj.toJson)
}

Is it correct? Is there any other (better) approach?

1

There are 1 answers

3
Nick Jacobs On BEST ANSWER

Consider using .getOrElse as I think it makes the intent a bit clearer and avoids a naked access to the left field:

  val playerSerde: Serde[Any, Player] = Serde.string.inmapM { playerAsString =>
    ZIO.effectTotal(playerAsString.fromJson[Player].getOrElse(throw new Error))
  }(playerAsObj => ZIO.effect(playerAsObj.toJson))

I also assumed that you meant .fromJson[Player] as I didn't see a Match class anywhere in your question.