Home > OS >  Scala, ZIO - how to return custom response in zio-http?
Scala, ZIO - how to return custom response in zio-http?

Time:09-03

do you know how I can return custom object as zio-http response? I created simple class:

final case class CustomerResponse(id: Int, name: String, age: Int)

object CustomerResponse {
      implicit val responseCodec: Codec[CustomerResponse] = deriveCodec[CustomerResponse]
    }

and now I would like to return this CustomerResponse as Http response object:

Http.collect[Request] { case Method.GET -> !! / "customer" => // Response.as CustomerResponse

I tried to use

Response.json(CustomerResponse(1, "a", 1))

but it didnt work. Do you know how should I do it?

CodePudding user response:

Great question.

I think you can use ZIO Json to accomplish this. I am using ZIO 2 which seems to mess some things up however

case class CustomerResponse(id: Int, name: String, age: Int)

object CustomerResponse {
  implicit val encoder: JsonEncoder[CustomerResponse] = DeriveJsonEncoder.gen[CustomerResponse]
}

object CustomerServer extends ZIOAppDefault {
  val app: HttpApp[Any, Nothing] = Http.collect[Request] {
    case Method.GET -> !! / "customer" => Response.text(CustomerResponse(1, "w33b", 99).toJson)

  }

  override val run = Server.start(8090, app)


}
  • Related