Search code examples
scalarestplayframeworkplay2-mini

Split play2-mini Routes in several files


I'm pretty new to the whole Scala and Play thing so maybe my way solving this is not the right one. I'm using Scala 2.9.1 and play-mini_2.9.1-2.0.1.

I have an App.scala which usually contains the routes. But my intention is not to insert all possible routes in this file but split it by entities. In my case: User, Role, Process.

To achieve this I tried something like that:

//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
        } 
    }
  )
}

This is just the first step. My final goal is to load all objects (process, user etc.) dynamically from a specified package. Any ideas how this could be done?


Solution

  • You can use orElse to combine the routes:

    val routes = User.routes orElse Process.routes
    

    In fact using, the Routes.apply method that you invoke when you write val routes = Routes(...) will return a scala PartialFunction which defines the method orElse used above.

    Pay attention to the order, in my example the routes in User.routes will be tested for a match before the routes in Process.routes.