Last active
March 7, 2016 10:07
-
-
Save megaherz/bb85a12d868b44a8fe4c to your computer and use it in GitHub Desktop.
Fetch exchange rates in Play2
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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