Todor Kolev Todor Kolev - 6 days ago 6
Scala Question

How to forward a WSResponse without explicitly mapping the result

So I have the following action and I would like to find a way to directly return the response without having to map it to a result for every possible status code i.e skip the if-else part.

def testAction = Action { implicit requestIn => {

val requestOut : WSRequest = WS.url("test-domain-name:9998")

val queryString = requestIn.queryString.map { case (k,v) => k -> v.mkString }

val futureResponse : Future[WSResponse] = requestOut.withQueryString(queryString.toList: _*).get()

val response = Await.result(requestOut.withQueryString(queryString.toList: _*).get(), 5 seconds)

if(response.status == 200){
Ok(response.xml)
} else
BadRequest(response.body)
}


}

Answer

You should not await for result. Play framework supports async actions:

def testAction = Action.async { implicit requestIn =>

    val requestOut: WSRequest = WS.url("test-domain-name:9998")

    val queryString = requestIn.queryString.map { case (k, v) => k -> v.mkString }

    val futureResponse: Future[WSResponse] = requestOut.withQueryString(queryString.toList: _*).get()

    futureResponse

}

And implicit conversion:

implicit def Response2Result(response: Future[WSResponse]): Future[Result] = {
  response map {
    response =>
      val headers = response.allHeaders map {
        h => (h._1, h._2.head)
      }
      Result(ResponseHeader(response.status, headers), Enumerator(response.body.getBytes))
  }
}

See github issue.

Comments