如何使用play framework 2.5代理HTTP方法?

时间:2016-11-03 09:48:44

标签: scala playframework playframework-2.5

我有两个简单的API:

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

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

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

如何在不创建他们同时调用的辅助方法的情况下,getMyPhotos代理到getPhotos

1 个答案:

答案 0 :(得分:1)

您可以在此处使用Play Framework提供的反向路由

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

在你的情况下

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

如果您想要第一个动作的结果

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

我希望这就是你要问的问题。

编辑:

为了您的关注,这应该是一种正确的方法

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