gpt4 book ai didi

scala - 光滑的 3.0 : Idiomatic way to GET results from the database inside of Option (Scala Play Framework)

转载 作者:行者123 更新时间:2023-12-04 06:58:58 24 4
gpt4 key购买 nike

我有一个 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 Future 内部从 Model 返回为了能够写出这样的东西:

// 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)))
}
}
}

是否有意义?

最佳答案

只需调用headOption在你的结果而不是 head :
def findById(id: Int): Future[Option[Thing]] = db.run(filterQuery(id).result.headOption)

关于scala - 光滑的 3.0 : Idiomatic way to GET results from the database inside of Option (Scala Play Framework),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30775040/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com