Scala为两个路径变量播放隐式路径绑定器

时间:2016-04-27 20:52:01

标签: scala rest playframework

我想为此网址PathBinder编写隐式/repo/:owner/:name,我的控制器应该是这样的:

case class GitHubRepositoryId(owner: String, name: String)
def get(repoId: GitHubRepositoryId) = {}

可以写一个吗?从play docs我无法找到解决方案。只有QueryStringBindable可以从URL访问多个变量并从那些构造POJO。

提前感谢

1 个答案:

答案 0 :(得分:1)

将您的路线更改为GET /repo/*repoId controllers.Controller.get(repoId: GitHubRespositoryId)

然后定义PathBindable,以便手动解析所有者和名称之间的/。像这样:

implicit val pathBinder = new PathBindable[GitHubRepositoryId] {
  override def bind(key: String, value: String): Either[String, GitHubRepositoryId] = {
    val parts = value.split('/')
    if (parts.size != 2) {
      Left("Not found")
    } else {
      Right(GitHubRepositoryId(parts(0), parts(1)))
    }
  }

  override def unbind(key: String, repoId: GitHubRepositoryId): String = {
    s"${repoId.owner}/${repoId.name}"
  }
}