我在PlayFramework的控制器中有以下代码:
def auth = Action.async(parse.json) { request =>
{
val authRequest = request.body.validate[AuthRequest]
authRequest.fold(
errors => Future(BadRequest),
auth => {
credentialsManager.checkEmailPassword(auth.email, auth.password).map {
case Some(credential: Credentials) => {
sessionManager.createSession(credential.authAccountId).map { //Throws an error
case Some(authResponse: AuthResponse) => Ok(Json.toJson(authResponse))
case None => InternalServerError
}
}
case (None) => Unauthorized
}
})
}
}
我在上面有错误评论的行中收到以下错误:
Type Mismatch:
[error] found : scala.concurrent.Future[play.api.mvc.Result]
[error] required: play.api.mvc.Result
[error] sessionManager.createSession(credential.authAccountId).map {
createSession调用返回Future[Option[Object]]
,但我无法弄清楚如何解决这个问题。
非常感谢任何帮助。
答案 0 :(得分:3)
简短回答:
将第.map
行中的.flatMap
更改为credentialsManager.checkEmailPassword(auth.email, auth.password).map
,将case (None) => Unauthorized
更改为case None => Future(Unauthorized)
说明:
credentialsManager.checkEmailPassword(auth.email, auth.password)
返回Future[Option[Credentials]]
,其上的映射将始终返回Future
,其中sessionManager.createSession(credential.authAccountId)
也会返回Future
因此,credentialsManager.checkEmailPassword(auth.email, auth.password)
的最终结果{1}} Future[Future[something]]
为了避免出现这种情况,您可以flatten
代替它map
它可以通过flatmap
答案 1 :(得分:1)
不确定,但这应该有效:
def auth = Action.async(parse.json) { request =>
{
val authRequest = request.body.validate[AuthRequest]
authRequest.fold(
errors => Future(BadRequest),
auth => {
credentialsManager.checkEmailPassword(auth.email, auth.password).flatMap { //flatMap
case Some(credential: Credentials) => {
sessionManager.createSession(credential.authAccountId).map {
case Some(authResponse: AuthResponse) => Ok(Json.toJson(authResponse))
case None => InternalServerError
}
}
case None => Future(Unauthorized) //Wrap it
}
})
}
}
这是对代码的简化,并附有一些注释。我希望这足以抓住这个想法:
Future(Option("validCredentials")).flatMap {
case Some(credential) => Future("OK")
case None => Future("Unauthorized")
}
//Future[Option[String]].flatMap(Option[String] => Future[String])
//Future[A].flatMap(A => Future[B]) //where A =:= Option[String] and B =:= String
答案 2 :(得分:0)
未来(“未经授权”)这是无效的请使用Future.successful(Ok(“OK”)) Future.successful(错误请求(未授权))