I have this code for an API
that allows me to retrieve and object from the database and return a JSON
object using 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)))
}
}
The problem is that if I query an object that is not in the database, I get an exception. What I would like to do is to get an Option
inside of the Future
that is returned from the Model
in order to be able to write something like this:
// 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)))
}
}
}
Does it make sense?
Simply call headOption
on your result instead of head
:
def findById(id: Int): Future[Option[Thing]] = db.run(filterQuery(id).result.headOption)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With