密钥删除!当方法是PUT时调用

时间:2014-04-20 08:19:45

标签: clojure monger liberator

我试图使用解放器和monger构建一个简单的rest api:

(ns tm.place.endpoint
  (:require [liberator.core :refer [defresource]]
            [monger [collection :as mc] [query :as mq]]
            [clojure.data [json :as json]]
            monger.json))

(defresource entity-place-resource [id]
  :available-media-types ["application/json"]
  :allowed-methods [:get :put :delete]
  :exists? (if-let [place (mc/find-map-by-id "place" id)] {:place place})
  :handle-ok :place
;  :handle-created (fn [ctx] 
;                     (let [body (-> ctx :request :body)]
;                       (assoc body :_id id)))
  :handle-not-found []
  :handle-not-acceptable "Should accept application/json"
  :handle-method-not-allowed (json/write-str 
                              {:message "Can only handle get, put and delete"})
;  :handle-not-implemented
;  :handle-no-content
  :put! (fn [ctx] 
          (let [body (-> ctx :request :body)]
            (mc/update-by-id "place" id (assoc body :_id id))))
  :delete! (mc/remove-by-id "place" id)
  :can-put-to-missing? false)

我使用advanced rest client查看是否有效。如果方法是:get:delete,则它完全符合我的要求(首先检查文档是否存在,然后执行相应的操作)。但是,如果方法是:put,它只会吐出创建的http 201,我认为请求成功,但相应的文档被删除,没有更新。

如果我评论出来:删除!行,:放!是按预期工作,所以我猜测罪魁祸首是:delete!行,但我不明白为什么因为我使用:put方法,我假设:删除!应该保持不变。知道为什么吗?

1 个答案:

答案 0 :(得分:2)

正如您已定义删除!作为一项简单的功能,当你不期待它时,它会被评估。你遵循的模式!需要应用,你返回一个fn来完成工作而不是直接行动。

http://clojure-liberator.github.io/liberator/faq.html

由于defresource宏扩展的确切细节,用作值的表单将在意外时间进行评估。