在Scala和Playframework中为嵌套类创建QueryStringBindable

时间:2014-06-24 22:47:53

标签: scala playframework-2.0 nested query-string

我试图查看是否可以为以下内容创建QueryStringBindable。 我有两个案例BoundingBoxFilter,其中有两个Location s

case class Location(lat: Double, lon: Double) {
  def isEmpty: Boolean = {
    lat == 0.0 && lon == 0.0
  }
}

case class BoundingBoxFilter(start: Location, end: Location) {
  def isEmpty: Boolean = {
    start.isEmpty && end.isEmpty
  }
}

现在我想定义路线

   /filterByLocation      MyController.filter(b: BoundingBoxFilter) 

1 个答案:

答案 0 :(得分:3)

那么,您希望网址实际上是什么样的?您希望调用查询字符串参数是什么?我们假设你想给他们打电话slatslonelatelon

这样的东西?

object BoundingBoxBindable extends QueryStringBindable[BoundingBox] {
  def bind(key: String, params: Map[String, Seq[String]]) = {
    for {
      slat <- params.get("slat")
      slon <- params.get("slon")
      elat <- params.get("elat")
      elon <- params.get("elon")
    } yield {
      try {
        Right(BoundingBox(Location(slat.toDouble, slon.toDouble), Location(elat.toDouble, elon.toDouble)))
      } catch {
        case e: Exception => Left(e.getMessage)
      }
    }
  }
  def unbind(key: String, v: BoundingBox) = {
    s"slat=${v.start.lat}&slon=${v.start.lon}&elat=${v.end.lat}&elon=${v.end.lon}"
  }
}

There is good example on the PlayFramework API Documentation