斯卡拉玩未来的相互依赖

时间:2016-06-12 07:12:24

标签: scala playframework-2.0 dao future data-access-object

我正在使用play-slick进行我的scala Play!虚拟休息API。

所以,我必须从多个表中获取记录。但是,它们是相互依存的,即

Table_1   Table_2
id1       id2
id2

要从Table_2中获取记录,我必须从Table_1中获取记录,然后使用表2中的id2 fetch。

我的控制器:

def getEntity(id : Long) = Action.async {
  table1DAO.findById(id) map { t1 =>
    t1 map { t1Entity =>
      table2DAO.findById(t1Entity.id2) map { t2 =>
        t2 map { t2Entity =>
          Ok(Json.toJson(CombiningClass(t1Entity, t2Entity)))
        } getOrElse { Ok(Json.toJson(t1Entity)) }
      }
    } getOrElse { NoContent }
  }
}

编译完成后,我得到:

[error] DummyController.scala:17: 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 getEntity(id : Long) = Action.async {
[error]                                ^
[error] one error found

这是我的DAO方法:

def findById(id : Long): Future[Option[A]] = {
  db.run(tableQ.filter(_.id === id).result.headOption)
}
PS:我对功能范式和scala非常陌生,所以如果可以的话,请原谅我的无知。

1 个答案:

答案 0 :(得分:1)

简单地解决您的问题:

def getEntity(id : Long) = Action.async {
  findById(id) flatMap {
    case Some(t1Entity) =>
      findById(t1Entity.id2) map { t2Opt =>
        t2Opt map { t2Entity =>
          Ok(Json.toJson(t1Entity, t2Entity))
        } getOrElse { Ok(Json.toJson(t1Entity)) }
      }
    case None => Future.successful(NoContent)
  }
}

此处的问题是您无法在scala中flatMap OptionFutureHere是关于此主题的精彩而简单的文章(将自定义FutureO monad实现作为解决方案)。长话短说,我会使用cats库(甚至是scalaz库)和OptionT功能。我略微简化了你的代码。

def getEntity(id : Long) = Action.async {
  (for {
    t1 <- daoFindById(id)
    t2 <- daoFindById(t1.id2)
  } yield (t1, t2)).map{
    result => Ok(Json.toJson(result))
  }.getOrElse(NoContent)
}

case class T(id2: Long)
def daoFindById(id : Long): OptionT[Future, T] = {
  OptionT[Future, T](db.run(tableQ.filter(_.id === id).result.headOption))
}

您现在可以轻松flatMap超过此OptionT monad,并且不关心您是否正在处理OptionFuture(因为scala中的理解只是一个句法糖)。

相关问题