I've a scala project with http4s 0.15.16a and slick 3.2.1 with these steps:
- Receive a ID by rest call
- passing ID to MySlickDAO that responds with a Future
- Call Await.result(res, Duration.Inf) on Future returned by MySlickDAO
- Create the json
The problem is that I use a Await.result and this is bad practices is there a better solution ?
Here the code:
val service = HttpService {
//http://localhost:8080/rest/id/9008E75A-F112-396B-E050-A8C08D26075F
case GET -> Root / "rest" / "id" / id =>
val res = MySlickDAO.load(id)
Await.result(res, Duration.Inf)
val ll = res.value.get.get
ll match {
case Failure(x) =>
InternalServerError(x)
case Success(record) =>
val r = record.map(x => MyEntity(x._1, x._2, x._3))
jsonOK(r.asJson)
}
case ....
}
Instead of awaiting, you can chain the result of one
Future
into another:The result of this will be a
Future
of a common supertype ofjsonOK
andInternalServerError
(not familiar with the libraries you're using; so I may have the type of load wrong: it's not aFuture[Try[_]]
is it?).BTW: your original code has a very problematic line:
res.value
is anOption[Try[T]]
. Callingget
on anOption
or aTry
is generally a bad idea (even though in this case because of theAwait
, theOption
should never beNone
, so theget
is technically safe) because it can throw an exception. You're much better off usingmap
,flatMap
, and friends.