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

play framework 2.5 move Action.async logic from controller to service

我有一个包含许多业务逻辑的控制器,我想将代码移动到 Action.async 代码块中。此代码有效,我如何移动到另一个 class(service) 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
}

我已经检查了文档,一些与 create a Future[Result] 有关的内容,但我无法使函数 returns 与 Action.async 期望的类型相同。

Action.async 需要一个 return 类型的 Future[Result] 所以你需要创建一个 return 是 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"))
  }
}