green-creeper green-creeper - 3 months ago 17
Scala Question

Scala future with akka-http

I need to write simple web service with akka-http and reactivemongo.

Function to save data looks like this

def saveRoute(route: Route):Future[WriteResult] = {
collection.insert(route)
}


a code that calls this function looks like this

val userRoutes = {
logRequestResult("akka-http-microservice") {
path("routes") {
(post & entity(as[Route])) { route =>
Database.saveRoute(route)
}
}
}
}


I need to return result with inserted ID of Route and do this without making the thread to wait.
if try

Database.saveRoute(route).onComplete{
case Success(r) => complete(r.toString)
case Failure(e) => complete(e.getMessage)
}


It cannot compile, because it doesn't return value.
I know how to make it in dirty way, but really want to make in appropriate manner.

What should be done in this case?

Answer

Seems like I've found most efficient way to do this. It's built in onComplete directive

(path("routes" / "add") & post & entity(as[Route])) {
    route =>
      onComplete(routesController.addRoute(route)) {
        case Success(result) => complete(StatusCodes.Created, "OK")
        case Failure(ex) => complete(new ErrorResponse(StatusCodes.InternalServerError.intValue, ErrorResponse.ERROR, ex.getMessage))
      }
  }