Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are imports and conditionals in Play's routes file possible?

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()
like image 580
pathikrit Avatar asked Aug 04 '14 17:08

pathikrit


1 Answers

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.

like image 73
Dmitriy Yefremov Avatar answered Oct 27 '22 00:10

Dmitriy Yefremov