Scala Play Framework 2.6 - 定义使用自定义对象的路由

Scala Play Framework 2.6 - define routes consuming custom objects

在包 models 中,我有以下情况 class:

case class Property (id: Option[Long],
                 address: String,
                 postCode: Int,
                 latitude: Double,
                 longitude: Double,
                 surface: Option[Int],
                 bedRoomCount: Option[Int])

object Property {
    implicit val propertyFormat = Json.format[Property]
}

我正在尝试配置传递 属性 对象的路由:

POST    /update-property            controllers.PropertyController.update(property: models.Property)

我的控制器定义了一个动作:

def update(property: Property) = Action.async { implicit request =>
 ...bla bla bla...
}

我得到以下编译错误:

[error] conf/routes:8:1: No QueryString binder found for type models.Property. Try to implement an implicit QueryStringBindable for this type.
[error] POST    /update-property            controllers.PropertyController.update(property: models.Property)
[error] conf/routes:8:1: not enough arguments for method implicitly: (implicit e: play.api.mvc.QueryStringBindable[models.Property])play.api.mvc.QueryStringBindable[models.Property].
[error] Unspecified value parameter e.

我错过了什么?是否可以使用 property 数据填充表单?

如编译错误所说,您需要实现一个implicit QueryStringBindable。像这样:

object Binders {

  //return the error message on the left should the parsing fail
  private def propertyFromString(s: String): Either[String, Property] = ???

  private def propertyToString(property: Property): String = ???

  implicit def queryStringBindable(implicit stringBinder: QueryStringBindable[String]): QueryStringBindable[Property] = new QueryStringBindable[Property] {
    override def bind(key: String, params: Map[String, Seq[String]]): Option[Either[String, Property]] = {
      for {
        eitherPropString <- stringBinder.bind("property", params)
      } yield {
        eitherPropString match {
          case Right(propString) => propertyFromString(propString)
          case _ => Left("Unable to bind property")
        }
      }
    }
    override def unbind(key: String, property: Property): String = {
      stringBinder.unbind("property", propertyToString(property))
    }
  }

}

对于???,您需要将代码写入encode/decode a Property to/from a String。然后,在您的 build.sbt 文件中,添加

routesImport += "path.to.Binders._"

这样您的 routes 文件就可以访问您的 Binders 对象。文档是 here。相反,如果您想将 Property 字段作为单独的查询参数传递,请参阅文档中的 AgeRange 示例。