mapRouteResultWith

Signature

def mapRouteResultWith(f: RouteResult => Future[RouteResult]): Directive0

Description

Changes the message the inner route sends to the responder.

The mapRouteResult directive is used as a building block for Custom Directives to transform the RouteResult coming back from the inner route. It’s similar to the mapRouteResult directive but returning a FutureCompletionStage instead of a result immediately, which may be useful for longer running transformations.

See Result Transformation Directives for similar directives.

Example

Scala
sourcecase object MyCustomRejection extends Rejection
val rejectRejections = // not particularly useful directive
  mapRouteResultWith {
    case Rejected(_) => Future(Rejected(List(AuthorizationFailedRejection)))
    case res         => Future(res)
  }
val route =
  rejectRejections {
    reject(MyCustomRejection)
  }

// tests:
Get("/") ~> route ~> check {
  rejection shouldEqual AuthorizationFailedRejection
}
Java
sourceimport static akka.http.javadsl.server.Directives.mapRouteResultWith;

import static akka.http.javadsl.server.Directives.mapRouteResultWith;
import static akka.http.javadsl.server.Directives.reject;

final Route route = mapRouteResultWith(rr -> CompletableFuture.supplyAsync(() -> {
  if (rr instanceof Rejected) {
    final Iterable<Rejection> rejections =
      Collections.singletonList(Rejections.authorizationFailed());
    return RouteResults.rejected(rejections);
  } else {
    return rr;
  }
}), () -> reject(new MyCustomRejection()));

// tests:
runRouteUnSealed(route, HttpRequest.GET("/"))
  .assertRejections(Rejections.authorizationFailed());
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.