Search code examples
scalaakkaakka-streamakka-http

Akka Streams / HTTP: Get original request from response


I have an Akka Streams source that goes through a flow and posts an HTTP request:

source.map(toRequest)
  .via(Http().outgoingConnection(host))
  .map(toMessage) 

Suppose that the toRequest method maps a string to an HttpRequest, and the toMessage method maps the HttpResponse to a message class that is needed to process downstream. Suppose that the message class needs to contain some of the original information.

Is it possible to get the original HttpRequest from the HttpResponse? If not, is there any way to keep some of the original information?


Solution

  • One approach is to use a Future-based variant of the client API and a custom case class that holds the information you want to propagate downstream. For example:

    case class Message(request: HttpRequest, response: HttpResponse)
    
    source
      .map(toRequest)
      .mapAsync(parallelism = 3) { request => // adjust the level of parallelism as needed
        Http().singleRequest(request).map(response => Message(request, response))
      }
      // continue processing; at this point you have a Source[Message, _]