如何使用 play framework 2.5 代理 HTTP 方法?
How to proxy an HTTP method with play framework 2.5?
我有 2 个简单的 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
?
这里可以使用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))
}
}
我有 2 个简单的 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
?
这里可以使用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))
}
}