Reputation: 21
I have a controller that has many business logic, I would like to move the code inside Action.async block of code. This code works, how can I move to another class(service) the code that is inside of the 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
}
I have been checked the docummentation, something related to create a Future[Result] but I am not be able to make that the function returns the same type that Action.async expect.
Upvotes: 0
Views: 75
Reputation: 2414
Action.async
expects a return type of Future[Result]
so you need to create a function that returns a Future[Result]
First step, extract your code to a function:
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("...")
}
}
Then in the controller call your function:
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"))
}
}
Upvotes: 1