如何使这个函数尾递归?

时间:2016-12-23 11:33:35

标签: scala playframework

如何使这个函数尾递归(即@tailrec):

package controllers

import javax.inject._

import play.api.Configuration
import play.api.libs.concurrent.Execution.Implicits.defaultContext
import play.api.libs.json._
import play.api.libs.ws.{WSClient, WSResponse}
import play.api.mvc._

import scala.collection.JavaConverters._
import scala.concurrent.Future

@Singleton
class ServiceController @Inject()(ws: WSClient, configuration: Configuration) extends Controller {

  def service = Action.async { implicit request =>
    val services = configuration.getStringList("primable-services").get.asScala.toList
    serviceAux(request.body.asJson.get, services)
  }

  // TODO should @tailrec
  private def serviceAux(in: JsValue, services: List[String]): Future[Result] = {
    services match {
      case Nil => Future(Ok(in))
      case head :: tail =>
        ws.url("http://" + head + ":9000/service")
          .withHeaders("Content-Type" -> "application/json")
          .withHeaders("Accept" -> "application/json")
          .put(in)
          .flatMap { response =>
            if (response.status != 200)
              Future(BadGateway(formatError(response)))
            else
              serviceAux(Json.toJson(response.body), tail)
          }
    }
  }

  private def formatError(response: WSResponse) = {
    JsObject(Seq("code" -> JsString("ERROR"), "response" -> JsObject(Seq("statusCode" -> JsNumber(response.status), "body" -> JsString(response.body)))))
  }
}

0 个答案:

没有答案