2

I have (formerly) REST spray.io webservice. Now, I need to generate SESSIONID in one of my methods to be used with some other methods. And I want it to be in the response header.

Basically, I imagine logic like the following:

 path("/...") {
   get {
     complete {
       // some logic here
       // .....
       someResult match {
         case Some(something) =>
           val sessionID = generateSessionID
           session(sessionID) = attachSomeData(something)
           // here I need help how to do my imaginary respond with header
           [ respond-with-header ? ]("X-My-SessionId", sessionID) {
             someDataMarshalledToJSON(something)
           }


         case None => throw .... // wrapped using error handler
       }
     } 
   }
 }

But, it doesn't work inside complete, I mean respondWithHeader directive. I need an advice.

dmitry
  • 4,989
  • 5
  • 48
  • 72

1 Answers1

5

There is a respondWithHeader directive in Spray. Here is official doc and example of how you could use it:

 def respondWithSessionId(sessionID: String) =
   respondWithHeader(RawHeader("X-My-SessionId", sessionID))

 path("/...") {
   get {
       // some logic here
       // .....
       sessionIDProvider { sessionID =>
           respondWithMediaType(`application/json`) { // optionally add this if you want
             respondWithSessionId(sessionID) {
               complete(someDataMarshalledToJSON(something))
             }
           }
       }
   }
 }
yǝsʞǝla
  • 16,272
  • 2
  • 44
  • 65
  • They say that code outside the complete will be evaluated at route construction time, won't it bring undesired effects here? Also I have some `validate()` and `params()` directives currently before `complete`. – dmitry Jul 28 '14 at 08:51
  • Yep that's right, I just was lazy to move everything into `complete`. Just wrap things with directives like: `params { validate { ... } }`. I prefer to keep all these variables out of the route and call some function instead to keep the route very simple and clear. – yǝsʞǝla Jul 28 '14 at 08:58
  • Thanks, I found simpler solution though for my particular case: `provide(generateSessionId) { sessionId => respondWithHeader(.., sessionId) { complete and the rest unchanged, can use sessionId inside } } `. – dmitry Jul 28 '14 at 09:10
  • Could you update the answer with the correct solution? I need to add a Raw/Custom header myself and I'm a bit confused as to how to do it. – djsumdog Oct 21 '16 at 20:35
  • @djsumdog just use `respondWithHeader(RawHeader("your_header_name", header_value)) { ... your code that completes the route ... }` as shown in the answer. For instance: `respondWithHeader(RawHeader("MYHEADER", "123")) { complete("test") }` – yǝsʞǝla Oct 22 '16 at 00:27