I know that the earlier versions of Play used to support routes and conditionals (if blocks) in the routes file but I cannot find any such documentation for Play 2.2.x and HTTP routing says nothing about such a feature.
I want to replace this:
GET /api/users/:id com.corporate.project.controllers.UserController.get(id)
with a shorter version using import
as follows:
import com.corporate.project.controllers._
GET /api/users/:id UserController.get(id)
Also, is it possible to have conditionals in the routes file? e.g.
if Play.isDev(Play.current())
GET /displayConfig DebugController.displayServerConfigs()
Package imports used to be possible with an SBT setting: routesImport += "com.corporate.project.controllers._"
. Not sure if it is still the case.
Also, is it possible to have conditionals in the routes file?
It might not be an ideal solution but we use routes tags to deal with this kind of conditional routes. You need a filter that checks if the route is annotated and runs your conditional logic.
Routes:
# @devmode
GET /displayConfig DebugController.displayServerConfigs()
Filter:
object DevmodeRouteFilter extends Filter {
private val DevmodeAnnotation = "@devmode"
override def apply(next: RequestHeader => Future[SimpleResult])(request: RequestHeader): Future[SimpleResult] = {
if(isDevRoute(request) && !Play.isDev(Play.current()) {
Play.current.global.onHandlerNotFound(request)
} else {
next(request)
}
}
private def isDevRoute(request: RequestHeader): Boolean = {
val comments = request.tags.getOrElse(Routes.ROUTE_COMMENTS, "")
comments.lines.exists { comment =>
comment.trim == DevmodeAnnotation
}
}
}
Don't forget to add the filter to the filter chain.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With