我正在尝试构建一个自定义的Akka HTTP指令,该指令将响应异步映射到另一个响应。给出以下定义:
trait ResponseFilter {
def apply(request: HttpRequest, response: HttpResponse): Future[HttpResponse]
}
我想建立与此类似的指令(不会编译):
def filterResponse(responseFilter: ResponseFilter): Directive0 = {
extractRequest { request =>
mapResponse { response =>
responseFilter(request, response)
}
}
}
编译器错误为:
...type mismatch;
[error] found : scala.concurrent.Future[akka.http.scaladsl.model.HttpResponse]
[error] required: akka.http.scaladsl.model.HttpResponse
[error] responseFilter(request, response)
[error] ^
[error] one error found
这很有意义,因为mapResponse
是同步的。
我知道onSuccess
,但似乎无济于事。
答案 0 :(得分:0)
我在Akka HTTP来源上花了一些时间,并提出了以下解决方案,该解决方案似乎可以正常工作:
def filterResponse(responseFilter: ResponseFilter): Directive0 = {
Directive { inner => ctx =>
implicit val ec = ctx.executionContext
inner(())(ctx).flatMap {
case result: Complete =>
responseFilter(ctx.request, result.response).map { filteredResponse =>
RouteResult.Complete(filteredResponse)
}
case incomplete => Future.successful(incomplete)
}
}
}
如果有更好的方法,请告诉我!