现在可以使用的Compojure这样:有没有办法让compojure支持自动类型转换?
(GET ["/uri"] [para1 para2]
)
PARA1和PARA2都是String类型。
我想让它correcttly知道是什么类型,像这样:
(GET ["/uri"] [^String para1 ^Integer para2]
)
它可以转换PARA1是斯汀和PARA2为整型。
有没有一些图书馆或好办法做到这一点?
现在可以使用的Compojure这样:有没有办法让compojure支持自动类型转换?
(GET ["/uri"] [para1 para2]
)
PARA1和PARA2都是String类型。
我想让它correcttly知道是什么类型,像这样:
(GET ["/uri"] [^String para1 ^Integer para2]
)
它可以转换PARA1是斯汀和PARA2为整型。
有没有一些图书馆或好办法做到这一点?
这目前不可能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¶2=3" :request-method :get})
{:status 200,
:headers {"Content-Type" "text/html; charset=utf-8"},
:body "{:k1 \"a\", :k2 4}"}
这是可能的的Compojure 1.4.0使用语法[x :<< as-int]