mapResponseEntity

Signature

def mapResponseEntity(f: ResponseEntity 

Description

The mapResponseEntity directive is used as a building block for Custom Directives to transform a response entity that was generated by the inner route.

See Response Transforming Directives for similar directives.

Example

Scala
sourcedef prefixEntity(entity: ResponseEntity): ResponseEntity = entity match {
  case HttpEntity.Strict(contentType, data) =>
    HttpEntity.Strict(contentType, ByteString("test") ++ data)
  case _ => throw new IllegalStateException("Unexpected entity type")
}

val prefixWithTest: Directive0 = mapResponseEntity(prefixEntity)
val route = prefixWithTest(complete("abc"))

// tests:
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "testabc"
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.mapResponseEntity;

final Function<ResponseEntity, ResponseEntity> prefixEntity =
    entity -> {
      if (entity instanceof HttpEntity.Strict) {
        final HttpEntity.Strict strict = (HttpEntity.Strict) entity;
        return HttpEntities.create(
            strict.getContentType(), ByteString.fromString("test").concat(strict.getData()));
      } else {
        throw new IllegalStateException("Unexpected entity type");
      }
    };

final Route route = mapResponseEntity(prefixEntity, () -> complete("abc"));

testRoute(route).run(HttpRequest.GET("/")).assertEntity("testabc");