How to decouple the POST parameters and the JSON body along the same route?

I have this route:

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

This works well, I can call my ElevationService following:

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

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

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

I managed to get it to work on 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 do not know how to combine these two routes into one. Since they are wrapped in functions, I cannot call params long , lat from the entity function, they do not exist in this area, I suppose. The same thing happens or vice versa.

I want to have access to both my parameters and my POST body, and then call a service that passes all the data:

 val elevationService = actorRefFactory.actorOf(Props(new ElevationService(requestContext))) elevationService ! ElevationService.Process(long, lat, bodyParams) 
+7
scala spray spray-dsl
source share
1 answer

You can simply attach 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 more directly combine the two directives:

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

All Articles