7

我有这条路线:

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
}

我已经设法让它按照实体指令的文档在单独的路线上工作:

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

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

我希望能够访问我的参数和我的 POST 正文,然后调用一个传递所有数据的服务:

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

1 回答 1

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) => ...
于 2014-12-30T15:06:20.063 回答