有没有办法让compojure自动支持类型转换?

时间:2015-01-17 15:51:38

标签: clojure type-conversion ring compojure

现在可以这样使用compojure:

(GET ["/uri"] [para1 para2]
   )

Para1和para2都是String类型。

我想让它知道正确的类型,如下:

(GET ["/uri"] [^String para1 ^Integer para2]
   )

它可以将para1转换为Sting,将para2转换为Integer。

是否有一些图书馆或好方法可以做到这一点?

2 个答案:

答案 0 :(得分:3)

从使用[x :<< as-int]

语法Compojure 1.4.0开始,这是可能的

答案 1 :(得分:0)

目前无法with only Compojure

您可以使用Prismatic schema coercion

(require '[schema.core :as s])
(require '[schema.coerce :as c])
(require '[compojure.core :refer :all])
(require '[ring.middleware.params :as rparams])

(def data {:para1 s/Str :para2 s/Int s/Any s/Any})
(def data-coercer (c/coercer data c/string-coercion-matcher ))

(def get-uri
  (GET "/uri" r
        (let [{:keys [para1 para2]}  (data-coercer (:params r))]
                 (pr-str {:k1 para1 :k2 (inc para2)}))))

(def get-uri-wrapped
  (let [keywordizer (fn [h]
                      (fn [r]
                        (h (update-in r [:params] #(clojure.walk/keywordize-keys %)))))]
    (-> get-uri keywordizer rparams/wrap-params)))

以下是一个示例运行:

(get-uri-wrapped {:uri "/uri" :query-string "para1=a&para2=3" :request-method :get})

{:status 200,
 :headers {"Content-Type" "text/html; charset=utf-8"},
 :body "{:k1 \"a\", :k2 4}"}
相关问题