【问题标题】:Scala Spray Routing - two HTTP method directives executed for single requestScala Spray Routing - 为单个请求执行的两个 HTTP 方法指令
【发布时间】:2015-05-08 10:10:14
【问题描述】:

这是我的路线:

pathPrefix("event" / Segment / "user") { id =>
    pathEnd {
        put {
            dbService.addParticipant(id, user)
            complete("OK")
        } ~
        delete {
            dbService.removeParticipant(id, user)
            complete("OK")
        }
    }
} ~  

当向http://localhost:9999/event/860852c4-768f-430e-9a9d-d1d35e86ede2/user 发送 PUT 或 DELETE 请求时,两个方法指令都被执行 - 我的意思是 dbService.addParticipant(id, user)dbService.removeParticipant(id, user) 被调用。谁能解释一下问题出在哪里?

我看不出这与 official spray example 有何不同:

// extract URI path element as Int
pathPrefix("order" / IntNumber) { orderId =>
  pathEnd {
    // method tunneling via query param
    (put | parameter('method ! "put")) {
      // form extraction from multipart or www-url-encoded forms
      formFields('email, 'total.as[Money]).as(Order) { order =>
        complete {
          // complete with serialized Future result
          (myDbActor ? Update(order)).mapTo[TransactionResult]
        }
      }
    } ~
    get {
      // JSONP support
      jsonpWithParameter("callback") {
        // use in-scope marshaller to create completer function
        produce(instanceOf[Order]) { completer => ctx =>
          processOrderRequest(orderId, completer)
        }
      }
    }
  }

【问题讨论】:

标签: scala rest spray


【解决方案1】:

作为@jrudolph pointed out,非叶提取指令内的代码(如在pathPrefix("order" / IntNumber) { orderId => 内,因为它需要从请求中提取的orderId 参数)在每个请求中执行,无论里面的指令是否是击中路线。叶指令中的代码(如complete)仅在路由匹配时执行。

要实现您可能想要的,只需将您的 dbService.addParticipant 移动到 complete 内:

pathPrefix("event" / Segment / "user") { id =>
    pathEnd {
        put {
            complete {
              dbService.addParticipant(id, user)
              "OK"
            }
        } ~
        delete {
            complete {
              dbService.removeParticipant(id, user)
              "OK"
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 2013-02-19
    • 2023-03-08
    • 2017-09-27
    • 2014-09-30
    • 2019-06-05
    相关资源
    最近更新 更多