Skip to content

Instantly share code, notes, and snippets.

@megaherz
Last active March 7, 2016 10:07
Show Gist options
  • Save megaherz/bb85a12d868b44a8fe4c to your computer and use it in GitHub Desktop.
Save megaherz/bb85a12d868b44a8fe4c to your computer and use it in GitHub Desktop.
Fetch exchange rates in Play2
package services
import javax.inject.Singleton
import play.api.libs.ws._
import play.api.Play.current
import scala.concurrent.Future
import scala.concurrent.ExecutionContext.Implicits.global
@Singleton
class ExchangeRateService
{
implicit def client = WS.client
def fetch(from: String, to: String): Future[Either[Error, Double]] = {
val url: String = s"https://www.google.com/finance/converter?a=1&from=$from&to=$to"
val response = WS.clientUrl(url).get()
response.map(res => {
val str = "<span class=bld>.+</span>".r.findFirstIn(res.body)
if (str.isDefined){
val rate = "[^0-9\\.]".r.replaceAllIn(str.get, "")
Right(rate.toDouble)
}
else {
Left(new Error(s"Invalid service response ${res.status} ${res.body}"))
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment