8

我有这个代码,API它允许我从数据库中检索和对象并JSON使用以下方法返回一个对象Slick 3.0

// Model

case class Thing(id: Option[Int], name: String)

object Thing {
  implicit val teamWrites = Json.writes[Thing]
}

class Things(tag: Tag) extends Table[Thing](tag, "thing") {
  def id = column[Int]("id", O.PrimaryKey, O.AutoInc)
  def name = column[String]("name")
  def * = (id.?, name) <> ((Thing.apply _).tupled, Thing.unapply)
}

object Things {
  private val db = Database.forConfig("h2mem1")
  private object things extends TableQuery[Things](tag ⇒ new Things(tag)) { 
    def all = things.result 
  }
  private def filterQuery(id: Int): Query[Things, Thing, Seq] = 
    things.filter(_.id === id)

  def findById(id: Int): Future[Thing] = db.run(filterQuery(id).result.head)
}
// Controller

class ThingController extends Controller {
  def get(id: Int) = Action.async {
    Things.findById(id).map(thing => Ok(Json.obj("result" -> thing)))
  }
}

问题是,如果我查询一个不在数据库中的对象,我会得到一个异常。我想做的是获取从返回的Option内部,以便能够编写如下内容:FutureModel

// Controller

class ThingController extends Controller {
  def get(id: Int) = Action.async {
    Things.findById(id).map {
      case None => NotFound(Json.obj("error" -> "Not Found"))) 
      case Some(thing) => Ok(Json.obj("result" -> thing)))
    }
  }
}

是否有意义?

4

1 回答 1

10

只需调用headOption您的结果而不是head

def findById(id: Int): Future[Option[Thing]] = db.run(filterQuery(id).result.headOption)

于 2015-06-11T08:10:13.640 回答