我正在尝试使用 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
or :delete
,它完全符合我的要求(它首先检查文档是否存在,然后执行适当的操作)。但是,如果方法是:put
,它只是简单地吐出http 201 created,我认为请求成功,但是相应的文档被删除,没有更新。
如果我注释掉 :delete! 线,:put!是按预期工作的,所以我猜罪魁祸首是这:delete!
条线,但我不知道为什么,因为因为我使用的是:put
方法,所以我假设:删除!应该保持不变。知道为什么吗?