scalasprayspray-jsonspray-dsl

How to unmarshal POST params and JSON body in a single route?


I have this route:

val routes =
    pathPrefix("api") {
      path("ElevationService" / DoubleNumber / DoubleNumber) { (long, lat) =>
        post {
          requestContext =>
            println(long, lat)
        }
      }
    }

This works nicely, I can call my ElevationService as:

http://localhost:8080/api/ElevationService/39/80

The problem is, I also want to parse the body sent to me in the request as JSON. It looks as follows:

{
  "first": "test",
  "second": 0.50
}

I've managed to get it to work in a separate route following the documentation on the entity directive:

path("test") {
   import scrive.actors.ScriveJsonProtocol
   import spray.httpx.SprayJsonSupport._
   post {
      entity(as[ScriveRequest]) { scrive =>
        complete(scrive)
      }
   }
}

But I don't know how to merge these two routes into one. Since they're wrapped in functions, I can't call the params long, lat from within the entity function, they doesn't exist in that scope I suppose. The same goes or the other way around.

I want to be able to access both my params and my POST body, and then call a service passing all the data:

val elevationService = actorRefFactory.actorOf(Props(new ElevationService(requestContext)))
elevationService ! ElevationService.Process(long, lat, bodyParams)

Solution

  • You can just nest the directives:

     path("ElevationService" / DoubleNumber / DoubleNumber) { (long, lat) =>
       post {
         entity(as[ScriveRequest]) { scrive =>
           onSuccess( elevationService ? ElevationService.Process(long, lat, bodyParams) ) {
             actorReply =>
               complete(actorReply)
           }
         }
     }
    

    You can also use & to combine two directives more directly:

    (path("ElevationService" / DoubleNumber / DoubleNumber) & entity(as[ScriveRequest])) {
      (long, lat, scriveRequest) => ...