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.
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
}
}