2
votes

I could find numerous examples on how to have an akka-http server easily marshal a response entity represented by a case class, by just mixing in SprayJsonSupport/DefaultJsonProtocol, providing a jsonFormat in implicit scope, and using the complete directive in the routing DSL. Neat!

However, i'd like to do something similar on the client side as well. I'm using the host-level API -provided connection pool flow ( clientFlow = Http.cachedHostConnectionPool ) to emit an (HttpRequest->context(T)) tuple like so:

(Source.single(request -> context)
.via(clientFlow)
.runWith(Sink.head).flatMap {
  case (Success(r: HttpResponse), c: T) => Future.successful(r)
  case (Failure(f), c: T) => Future.failed(f)
}, context)

the HttpRequest object is created via one of it's apply() methods

HttpRequest(
        method = HttpMethods.POST,
        uri = "/uri",
        entity = HttpEntity(contentType, """{"iWish":"i was an object"}"""))

on the server side, with the routing DSL ( with the right traits mixed in and jsonFormat for SomeCaseClass in implicit scope ) this looks something like:

complete(StatusCodes.BadRequest, SomeCaseClass(iWish = "i was an object"))

q: is there anything on the client-side APIs/DSLs that allow me to hide marshalling in a similar manner?

1

1 Answers

2
votes

You could have something like the following (if your Formats are in scope)

Marshal(yourObject).to[RequestEntity].map { entity =>
  HttpRequest(
    method = HttpMethods.POST,
    uri = "/uri",
    entity = entity)
}

(further reading here)