0

I have a filter of route handler using Spray Custom Directive0.

The purpose of this custom directive is to build a request filter to time the request processing time.

Inside the spray custom directive, I can use the RequestContext's function withHttpResponseMapped to take a parameter of HttpResponse => HttpResponse, and withHttpResponseMapped will return a new RequestContext object, like this:

 def timeRequestInterval: Directive0 = {
mapRequestContext { context =>
  val requestTimer = new RequestTimer(context.request)
  context.withHttpResponseMapped { response =>
    requestTimer.stop()
    response.mapEntity { entity =>
        entity
    }
  }
}

Now I try to migrate the custom directive from Spray to Akka-Http(2.4.8), but I cannot find withHttpResponseMapped or any function in RequestContext object that can take parameter of "HttpResponse => HttpResponse" and return a new RequestContext object. Is there any supported function or approach that can help me resolve this issue in Akka-Http Migration?

Thank you for the help in advance.

Alan
  • 15
  • 4

1 Answers1

2

The mapResponse directive is what you are looking for and then combine the directives with flatMap rather than apply:

val timeRequestInterval: Directive0 = extractRequestContext.flatMap { context =>
  val timer = new RequestTimer(context)
  mapResponse { response =>
    timer.stop()
    response
  }
}
johanandren
  • 11,249
  • 1
  • 25
  • 30
  • Thank you, Johan. It works now. Really appreciate your help. Alan – Alan Mar 10 '17 at 15:45
  • I'm trying a very similar flow and instead getting the following error: `type mismatch; [error] found : akka.http.scaladsl.server.Directive[Unit] required: akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult] extractRequestContext.flatMap { requestContext =>` – gregsilin Oct 02 '17 at 19:38