【问题标题】:Split play2-mini Routes in several files在几个文件中拆分 play2-mini 路由
【发布时间】:2012-10-02 04:16:02
【问题描述】:

我对整个 Scala 和 Play 还很陌生,所以我解决这个问题的方法可能不是正确的。我正在使用 Scala 2.9.1 和 play-mini_2.9.1-2.0.1。

我有一个通常包含路线的 App.scala。但我的意图不是在此文件中插入所有可能的路由,而是按实体拆分它。就我而言:用户、角色、流程。

为了实现这一点,我尝试了类似的方法:

//in App.scala
object App extends Application { 
  println("Checking Database")
  ...      
  println("Resume executions from database")
  ...      
  def route = Routes(Process.routes :: User.routes) // I know this is wrong but I think you get what I want to do...
}

//in Process.scala
object Process {
  val routes = Routes(
    {
        case GET(Path("/process")) => Action{ request =>
            // returns a list of processes
        }
        case GET(Path("/process")) & QueryString(qs) => Action{ request =>  
            val id = QueryString(qs,"id").getOrElse(0)
            // return process by id
        } 
    }
  )
}

//in User.scala
object User { 
  val routes = Routes(
    {
        case GET(Path("/user")) => Action{ request =>
            // returns a list of processes
        }
        case GET(Path("/user")) & QueryString(qs) => Action{ request =>     
            val id = QueryString(qs,"id").getOrElse(0)
            // return process by id
        } 
    }
  )
}

这只是第一步。我的最终目标是从指定的包中动态加载所有对象(进程、用户等)。任何想法如何做到这一点?

【问题讨论】:

    标签: scala rest playframework play2-mini


    【解决方案1】:

    您可以使用orElse 组合路由:

    val routes = User.routes orElse Process.routes
    

    事实上,当你编写val routes = Routes(...) 时调用的Routes.apply 方法将返回一个scala PartialFunction,它定义了上面使用的方法orElse

    注意顺序,在我的示例中,User.routes 中的路由将在Process.routes 中的路由之前进行匹配测试。

    【讨论】:

      猜你喜欢
      • 2010-12-27
      • 2020-11-09
      • 2018-03-05
      • 2011-11-10
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2011-09-14
      相关资源
      最近更新 更多