Skip to content

Instantly share code, notes, and snippets.

@little-hands
Last active June 30, 2019 13:08
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save little-hands/8b4373b3a5a27c62137c0c0570ba1262 to your computer and use it in GitHub Desktop.
Save little-hands/8b4373b3a5a27c62137c0c0570ba1262 to your computer and use it in GitHub Desktop.
package rakuten
import scalaj.http._
import net.liftweb.json._
import scala.util.{Failure, Success, Try}
trait RakutenTravelClient {
def keywordSearch(keyword: String): Either[Throwable, RakutenTravelApiResponse]
}
class RakutenTravelScalajClient(private val applicationId: String) extends RakutenTravelClient {
override def keywordSearch(keyword: String): Either[Throwable, RakutenTravelApiResponse] = {
implicit val formats: DefaultFormats.type = DefaultFormats
val response: HttpResponse[String] = Http(RakutenTravelScalajClient.url)
.param("format", "json")
.param("keyword", keyword)
.param("applicationId", applicationId)
.param("hits", "5")
.asString
Try(parse(response.body).extract[RakutenTravelApiResponse]) match {
case Success(v) => Right(v)
case Failure(thr) => Left(thr)
}
}
}
object RakutenTravelScalajClient {
private val url = "https://app.rakuten.co.jp/services/api/Travel/KeywordHotelSearch/20170426"
}
object TryRakuten extends App {
val applicationId = getRakutenApplicationId
.getOrElse(throw new RuntimeException("applicationIdが取得できませんでした"))
val client: RakutenTravelClient = new RakutenTravelScalajClient(applicationId)
println("search 新宿")
val shinjukuResponse: Either[Throwable, RakutenTravelApiResponse] = client.keywordSearch("新宿")
shinjukuResponse match {
case Right(v) => println(v.hotels)
case Left(err) => println(s"Fetch failed.\n${err.getMessage}")
}
def getRakutenApplicationId: Option[String] = {
Try(sys.env("RAKUTEN_APPLICATION_ID")) match {
case Success(v) => Some(v)
case Failure(_) => None
}
}
}
@xuwei-k
Copy link

xuwei-k commented Jun 30, 2019

  • Tryから、EitherやOptionに変換するだけなら、わざわざmatchして変換しなくても専用のtoEitherやtoOptionというメソッドがある
  • lift-jsonというライブラリは、昔は流行っていたが、リフレクションに起因する問題など微妙な部分が多くあり、最近はもっと優れているライブラリが多数出ていてあまり使われないライブラリなので、他のライブラリを使った方が良い

@xuwei-k
Copy link

xuwei-k commented Jun 30, 2019

sys.env.get("RAKUTEN_APPLICATION_ID") だけでOptionで取得出来る

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment