播放,您可以通過不同的方式來做到這一點
。
1 PathBindable
您可以實現PathBindable[T]
任何類型T
,使您從請求的路徑提取的值不是一個簡單的String
但T
。
如果你準備改變dynamic
類型(這將是有意義的,因爲它不應該是隨便一個字符串,但一個有效的),你可以做到以下幾點:
case class Validated(str: String) {
assert(Helper.validate(str))
}
object Validated {
implicit val pathBindable = new PathBindable[Validated] {
val string = implicitly[PathBindable[String]]
override def bind(key: String, value: String): Either[String, Validated] =
string.bind(key, value). // bind as if it were a string
right.filter(Helper.validate).getOrElse(Left("Invalid input")). // filter using your validation function, and give error message
right.map(Validated(_)) // encapsulate in your new type
override def unbind(key: String, value: Validated): String =
string.unbind(key, value.str) //unbind as if it were a string
}
}
注您需要爲反向路由實現unbind
(獲取給定操作調用的路徑)。
現在,您只需要在您的路由器和您的控制器中用替換your.package.Validated
。
GET /:dynamic/all controller.method(dynamic: your.package.Validated)
NB:如果你想使用你的類的簡單名稱,你需要將其導入您的build.sbt
:
(project in file(".").
enablePlugins(PlayScala).
settings(routesImport += "your.package.Validated")
(二)行動組成
你也可以實現一個動作過濾器,以便在您的輸入需要驗證時使用:
case class ValidatedAction(input: String) extends ActionFilter[Request] {
override protected def filter[A](request: Request[A]): Future[Option[Result]] = Future.successful{
if (Helper.validate(input)) None else Some(BadRequest("Invalid input"))
}
}
def method(dynamic: String) = (Action andThen ValidatedAction(dynamic)).async {
Future.successful(Ok)
}
的async
塊中的代碼將被執行僅當filter
方法返回None
,否則,它會返回指定Result
(這裏,BadRequest("Invalid input")
。
啊是的 - 非常感謝。我完全忘了考慮使用'ActionFilter'來做這種驗證。這對我來說似乎是一個很好的解決方案。同樣道具也適用於'PathBindable'解決方案。我很確定我遲早也會需要這個。 –