play framework 2.5将Action.async逻辑从控制器移动到服务

时间:2017-03-09 12:42:59

标签: scala asynchronous playframework controller playframework-2.5

我有一个具有许多业务逻辑的控制器,我想在 Action.async 代码块中移动代码。这段代码有效,如何将Action.async中的代码移动到另一个类(服务)?:

def tweetsnew(query: String) = Action.async {
// Move From Here...
credentials.map {
  case (consumerKey, requestToken) =>
    ws.url("https://api.twitter.com/1.1/search/tweets.json")
      .sign(OAuthCalculator(consumerKey, requestToken))
      .withQueryString("q" -> query)
      .withQueryString("max_id" -> "833342796736167936")
      .get().map { twitterResponse =>
      if (twitterResponse.status == 200) {
        // Here There Are More Complex Logic
        Ok("That is fine: "+twitterResponse.body)
      } else {
        throw new Exception(s"Could not retrieve tweets for $query query term")
      }
    }
}.getOrElse {
  Future.failed(new Exception("You did not correctly configure the Twitter credentials"))
}
//....To Here. To Another Class
}

我已经检查过docummentation,这与create a Future[Result]有关,但是我无法使该函数返回与Action.async期望的相同类型。

1 个答案:

答案 0 :(得分:1)

Action.async要求返回类型为Future[Result],因此您需要创建一个返回Future[Result]

的函数

第一步,将代码提取到函数中:

object TwitterService {
  def search(query: String, consumerKey: ConsumerKey, requestToken: RequestToken)(implicit ws: WSClient, ec: ExecutionContext): Future[Result] = {
    // your code that make the ws call that returns Ok("...")
  }
 }

然后在控制器中调用你的函数:

def tweetsnew(query: String) = Action.async {
  credentials.map {
    case (consumerKey, requestToken) => TwitterService.search(query, consumerKey, requestToken)
  }.getOrElse {
    // Better to send a bad request or a redirect instead of an Exception
    Future.successful(BadRequest("Credentials not set"))
  }
}