Slick 3.0: Idiomatic way to GET results from the database inside of Option (Scala Play Framework)

2k views Asked by At

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?

1

There are 1 answers

2
Roman On BEST ANSWER

Simply call headOption on your result instead of head:

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