stian
stian

Reputation: 1987

how to respond to a request with a dependency on another actor?

this might be a stupid question, but I need to ask since I havent found an answer to it yet. I have used the akka-http with routing with the typical routing pattern of a path with a
complete with a HttpRequest.

For instance:

~ path("reactJS") {
  complete(
    HttpResponse(entity = HttpEntity(ContentTypes.`text/html(UTF-8)`, Source.fromFile(reactJS).mkString))
  )
}

However, I would like to have a separate actor that handles a file system and then, in my mind, I would like the server to pass the request over to the file handler actor. So my question would be, how would one naturally do a complete of a request with a dependency on another actor? I guess then the server would have a routing looking like:

 ~ path("patient" / IntNumber) { index =>
      FileHandler ! index
   }

class FileHandler extends Actor{
  def receive = {
    case msg:Int => sender() ! file handling

}

and the serving of the request would have to be a case in the receive method of the server, right?

looking into:How to respond with the result of an actor call?

Upvotes: 0

Views: 81

Answers (1)

cmbaxter
cmbaxter

Reputation: 35443

I think your best bet is to use the ask pattern (?) and then use the onComplete directive within your routing tree to handle the Future that comes back from the ask. Taking your example, and modifying it a bit to show how you could leverage ask is shown below:

path("patient" / IntNumber) { index =>
  import akka.pattern.ask
  implicit val timeout = akka.util.Timeout(10 seconds)
  val fut = (fileHandlerActor ? index).mapTo[String]
  onComplete(fut){
    case util.Success(fileData) => 
      complete(HttpResponse(entity = HttpEntity(
        ContentTypes.`text/html(UTF-8)`, fileData))

    case util.Failure(ex) =>
      complete(HttpResponse(StatusCodes.InternalServerError))
  }
}

The assumption here is that your actor is responding with a String that is to become the HTTP response entity. Also, that timeout is a requirement of using ask, but you could very easily define it elsewhere in your code, as long as it's in scope here.

Upvotes: 2

Related Questions