Response Transformation
The counterpart to Request Building is the ResponseTransformation trait, which is especially useful on the client-side when you want to transform an incoming HTTP response in a number of loosely coupled steps into some kind of higher-level result type (see also spray-client).
Just like with RequestBuilding
the ResponseTransformation
trait gives you the ~>
operator, which allows
you to “append” a transformation function onto an existing function producing an HttpResponse
. Thereby it doesn’t
matter whether the result is a plain response or a response wrapped in a Future
.
For example, if you have a function:
import scala.concurrent.ExecutionContext.Implicits.global // for futures
val sendReceive: HttpRequest => Future[HttpResponse] = // ...
and a “response transformer”:
val removeCookieHeaders: HttpResponse => HttpResponse =
r => r.withHeaders(r.headers.filter(_.isNot("set-cookie")))
you can use the ~>
operator to combine the two:
import spray.httpx.ResponseTransformation._
val pipeline: HttpRequest => Future[HttpResponse] =
sendReceive ~> removeCookieHeaders
More generally the ~>
operator combines functions in the following ways:
X | Y | X ~> Y |
---|---|---|
A => B | B => C | A => C |
A => Future[B] | B => C | A => Future[C] |
A => Future[B] | B => Future[C] | A => Future[C] |
Predefined Response Transformers
- decode(decoder: Decoder): HttpResponse ⇒ HttpResponse
- Decodes a response using the given Decoder (
Gzip
orDeflate
). - unmarshal[T: Unmarshaller]: HttpResponse ⇒ T
- Unmarshalls the response to a custom type using the in-scope
Unmarshaller[T]
. - logResponse(...): HttpResponse ⇒ HttpResponse
- Doesn’t actually change the response but simply logs it.