scalasprayspray-dslspray-routing

How do you Nest different Spray Directives into 1 directive


Let's say I have 1 directive for authentication. And after authentication, I would like to log. This is what I do so far:

get(...) {
  myauthdirective() { v =>
     myloggingdirective(v) {
        ...
     }
  }
}

So I would like to covert that to a single directive instead of having to have 2 every time I need to authenticate.

I tried using flat map, but that doesn't seem to work because authenticate returns a Directive1 and logRequestResponse returns Directive0.

// Does not work!
authenticate(myAuthMagnet).flatMap {
  case ca: returnType => logRequestResponse(LoggingMagnet(logme(ca)))
}

So I tried it with map, but it doesn't seem to go into my logging magnet function.

// Does not work either!
authenticate(myAuthMagnet).map {
  case ca: returnType => 
    logRequestResponse(LoggingMagnet(logme(ca))) // does not go into logme function for some reason
    ca
}

I also can't call logme directly because I need the request and response objects as well.

Is there a way to create a new directive with 2 directives that return different Directive types? Thanks.


Solution

  • There is one little thing missing in your implementation. You need to provide value after logging. So the implementation should be like:

    authenticate(myAuthMagnet).flatMap {
      case ca: returnType => logRequestResponse(LoggingMagnet(logme(ca))) & provide(ca)
    }