jbrown jbrown - 1 month ago 10
Scala Question

How to proxy an HTTP method with play framework 2.5?

I have 2 simple APIs:

GET /users/me/photos controllers.api.UserController.getMyPhotos
GET /users/:userId/photos controllers.api.UserController.getPhotos(userId: Int)


Here's
getPhotos
:

def getPhotos(userId: Int) = SecuredAction.async {
logger.info(s"Searching for user $userId's photos")

userPhotosRepo.findByUserId(userId).map {
photos => Ok(Json.toJson(photos))
}
}


Here's
getMyPhotos
:

def getMyPhotos = SecuredAction.async { request =>

request.identity.id.map { currentUserId =>
logger.info(s"Searching for current user's photos")

getPhotos(currentUserId) // doesn't work
}.getOrElse(Future.successful(InternalServerError))
}


How can I make
getMyPhotos
proxy through to
getPhotos
without creating a helper method they both call?

Answer

Here you can use reverse routing provided by Play Framework

 [full package].routes.[controller].[method]

In your case

routes.api.UserController.getPhotos(request.identity.id)

If you want the result of first action

val ans: Result = Redirect(routes.api.UserController.getPhotos(request.identity.id))

I hope that's what you were trying to ask.

EDIT:

For your concern this should be a proper way to do it

def getPhotos(userId: Long) = SecuredAction.async {
  userPhotosRepo findByUserId(userId) map {
    photos => Ok(Json.toJson(photos))
  }
}

def getMyPhotos = SecuredAction.async { request =>
   request.identity.id map { id =>
       Redirect(routes.HomeController.getPhotos(id))
  }
 }