Home > Mobile >  scala how to wrap response to yield instead of val
scala how to wrap response to yield instead of val

Time:11-30

scala how to wrap this response to yield instead of val?

I have get method realization with vals, how can I refactor it with for yield structure

case Method.GET -> !! / "leagues" =>
  val openDotaResponse: ZIO[Client, Throwable, Response] = Client.request("https://api.opendota.com/api/leagues")
  val bodyOfResponse: ZIO[Client, Throwable, String] = openDotaResponse.flatMap(_.body.asString)
  val eitherListOfLeagues: ZIO[Client, Throwable, Either[String, List[League]]] = bodyOfResponse.map(_.fromJson[List[League]])
  val listOfLeagues: ZIO[Client, Throwable, List[League]] = eitherListOfLeagues.map(eitherList => eitherList.toOption.getOrElse(Nil))
  val result: ZIO[Client, Throwable, Response] = listOfLeagues.map(listLeagues => Response.json(listLeagues.toJson))
  result
case Method.GET -> !! / "4leagues" =>
//      val response1: ZIO[Client, Throwable, Response] = for {
//        openDotaResponse: ZIO[Client, Throwable, Response] <- Client.request("https://api.opendota.com/api/leagues")
//        bodyOfResponse: ZIO[Client, Throwable, String] <- openDotaResponse.flatMap(_.body.asString)
//        eitherListOfLeagues: ZIO[Client, Throwable, Either[String, List[League]]] <- bodyOfResponse.map(_.fromJson[List[League]])
//        listOfLeagues: ZIO[Client, Throwable, List[League]] <- eitherListOfLeagues.map(eitherList => eitherList.getOrElse(Nil))
//        result: ZIO[Client, Throwable, Response] <- listOfLeagues.map(listLeagues => Response.json(listLeagues.toJson)).map(_.body)
//        val res1: Response = result.map(_.body)
//        res1
//      } yield res1
      //response1

CodePudding user response:

Try

for {
  openDotaResponse <- Client.request("https://api.opendota.com/api/leagues")
  bodyOfResponse <- openDotaResponse.body.asString
  eitherListOfLeagues = bodyOfResponse.fromJson[List[League]]
  listOfLeagues = eitherListOfLeagues.toOption.getOrElse(Nil)
  result = Response.json(listOfLeagues.toJson)
} yield result

or just

for {
  openDotaResponse <- Client.request("https://api.opendota.com/api/leagues")
  bodyOfResponse <- openDotaResponse.body.asString
  eitherListOfLeagues = bodyOfResponse.fromJson[List[League]]
  listOfLeagues = eitherListOfLeagues.toOption.getOrElse(Nil)
} yield Response.json(listOfLeagues.toJson)

What is Scala's yield?

  • Related