如何设置路径参数的默认值?

时间:2018-10-22 11:44:30

标签: clojure compojure compojure-api

在下面的示例中,如何为路径参数item-id设置默认值?

(POST "/:id" [item-id]
  :path-params [item-id :- Int]
  :body [body Body]
  :query-params [{item-name :- Str nil}]
                 :summary "Create or update a item."
                 (ok ...))

1 个答案:

答案 0 :(得分:0)

您应该将路径参数名称与字符串占位符匹配。路径参数不需要默认值-如果不存在路径参数,则路由不匹配。这是一个工作示例:

(require '[compojure.api.sweet :refer :all])
(require '[ring.util.http-response :refer :all])
(require '[schema.core :as s])
(require '[muuntaja.core :as m])

(def app
  (api
    (POST "/:item-id" []
      :path-params [item-id :- s/Int]
      :query-params [{item-name :- s/Str nil}]
      :summary "Create or update a item."
      (ok {:item-id item-id
           :item-name item-name}))))

(->> {:request-method :post
      :uri "/123"
      :query-params {"item-name" "kikka"}}
     (app)
     :body
     (m/decode m/instance "application/json"))
; => {:item-name "kikka", :item-id 123}