Reactivemongo和Play,链接查询

时间:2015-01-07 11:29:49

标签: scala playframework future reactivemongo

Scala(最新),Reactivemongo(最新)和Play框架(2.3.x)有点新鲜。

验证会话,并在成功时加载用户对象,将其作为json返回。我想,问题是映射和期货特有的。以下代码不会编译:

def userCheck(token: String) = Action.async {
  val futureSession = sessionCollection.find(Json.obj("token" -> token)).one[BSONDocument]

  futureSession.map {
    case Some(session) => {
      userCollection.find(Json.obj("_id" -> session.getAs[String]("userId").get )).one[JsObject].map {
        case Some(user) => Ok(JsObject(Seq("user" -> user)))
        case None => NotFound( JsObject(Seq("message" -> JsString("not found"))) )
      }
    }
    // NotFound( JsObject(Seq("message" -> JsString("not found"))) )
    case None => NotFound( JsObject(Seq("message" -> JsString("not found"))) )
  }
}

所以,错误信息是:

[error] AuthController.scala:186: overloaded method value async with alternatives:
[error]   [A](bodyParser: play.api.mvc.BodyParser[A])(block: play.api.mvc.Request[A] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[A] <and>
[error]   (block: play.api.mvc.Request[play.api.mvc.AnyContent] => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent] <and>
[error]   (block: => scala.concurrent.Future[play.api.mvc.Result])play.api.mvc.Action[play.api.mvc.AnyContent]
[error]  cannot be applied to (scala.concurrent.Future[Object])
[error]   def userCheck(token: String) = Action.async {

如果你查看源代码,你会看到一个注释行,如果我取消注释它,代码就会编译。我想错过一些案例吗?

更新1:

所以,使用接受答案中的提示,我想出了这个:

def userCheck(token: String) = Action.async {
  getSession(token).flatMap {
    session => {
      session match {
        case Some(s) => {
          getUser( s.getAs[String]("userId").get ).flatMap {
            user => {
              user match {
                case Some(u) => Future.successful( Ok( u ) )
                case None => Future.successful( NotFound( JsObject(Seq( "m" -> JsString("User not found")))))
              }
            }
          }
        }
        case None => Future.successful( NotFound( JsObject(Seq( "m" -> JsString("Session not found")))))
      }
    }
  }
}

def getSession(token: String): Future[Option[BSONDocument]] = {
  sessionCollection.find( Json.obj("token" -> token) ).one[BSONDocument]
}

def getUser(id: String): Future[Option[JsObject]] = {
  userCollection.find( BSONDocument( "_id" -> BSONObjectID(id) ) ).one[JsObject]
}

......它可以解决问题。但是需要像重构这样的感觉。

1 个答案:

答案 0 :(得分:2)

尝试向所有分支添加显式类型;特别是,确保case Some(Session)之后的块返回Result或您认为应该是的任何内容。我怀疑在Some分支中你最终得到Future[Future[Result]]而不是Future[Result] - 也许你需要futureSession.flatMapNone案件返回Future.successful(...)