mapRouteResultWithPF

Signature

def mapRouteResultWithPF(f: PartialFunction[RouteResult, Future[RouteResult]]): Directive0

Description

Asynchronous variant of mapRouteResultPF.

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.

See Result Transformation Directives for similar directives.

Example

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

// tests:
Get("/") ~> route ~> check {
  rejection shouldEqual AuthorizationFailedRejection
}
Java
final Route route = mapRouteResultWithPF(
  new PFBuilder<RouteResult, CompletionStage<RouteResult>>()
  .match(Rejected.class, rejected -> CompletableFuture.supplyAsync(() -> {
    final Iterable<Rejection> rejections =
      Collections.singletonList(Rejections.authorizationFailed());
    return RouteResults.rejected(rejections);
  })
).build(), () -> reject(new MyCustomRejection()));

// tests:
runRouteUnSealed(route, HttpRequest.GET("/"))
  .assertRejections(Rejections.authorizationFailed());
The source code for this page can be found here.