简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM