3

I'm trying to nest existing akka http (version 10) directives to create my own custom directives. I'm having issues with things like this:

def echoHeaderDirective: Directive0 = optionalHeaderValueByName("X-Echo-Header") {
    case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))
    case _ => pass
}

The type being returned from the match is Directive0, but I get this error from IDEA

Expression of type Directive0 doesn't conform to expected type Route

and this error from the compiler

type mismatch;
[error]  found   : akka.http.scaladsl.server.Directive0
[error]     (which expands to)  akka.http.scaladsl.server.Directive[Unit]
[error]  required: akka.http.scaladsl.server.RequestContext => scala.concurrent.Future[akka.http.scaladsl.server.RouteResult]
[error]     case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))

is it possible to create custom directives in this style (nesting), and if so, what am I doing wrong?

kag0
  • 5,624
  • 7
  • 34
  • 67

1 Answers1

4

What you are doing is essentially applying the Directives by nesting them, as you would do to form your Route. And indeed, the final nesting level is expecting a Route (which is an alias for RequestContext ⇒ Future[RouteResult], as per SBT's complaint).

What you want to do is to transform Directives into other Directives, and to do so you should use map/flatMap functions. Example below:

  def echoHeaderDirective: Directive0 = optionalHeaderValueByName("X-Echo-Header") flatMap {
    case Some(value) => respondWithHeader(RawHeader("X-Echo-Header", value))
    case _ => pass
  }

More info here.

Stefano Bonetti
  • 8,973
  • 1
  • 25
  • 44