如何在单个路径中解组POST params和JSON body?

时间:2014-12-30 15:01:38

标签: scala spray spray-json spray-dsl

我有这条路线:

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

这很好用,我可以将ElevationService称为:

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

问题是,我还想在请求中解析发送给我的身体为JSON。它看起来如下:

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

我设法让它在the documentation on the entity directive之后的另一条路线上工作:

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

但我不知道如何将这两条路线合并为一条路线。由于它们已包含在函数中,因此我无法在long函数中调用参数latentity,它们不存在于该范围内我想。相反或相反。

我希望能够访问我的params和POST主体,然后调用传递所有数据的服务:

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

1 个答案:

答案 0 :(得分:7)

您可以嵌套指令:

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

您还可以使用&更直接地组合两个指令:

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