【问题标题】:Is there some way to let compojure support type conversion automatically?有没有办法让 compojure 自动支持类型转换?
【发布时间】:2015-01-17 15:51:38
【问题描述】:

现在可以这样使用 compojure:

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

para1 和 para2 都是 String 类型。

我想让它正确地知道类型,像这样:

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

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

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

【问题讨论】:

    标签: clojure type-conversion ring compojure


    【解决方案1】:

    从Compojure 1.4.0 开始可以使用[x :<< as-int] 语法

    【讨论】:

      【解决方案2】:

      这目前是不可能的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}"}
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2020-10-13
        • 1970-01-01
        • 2020-04-27
        • 1970-01-01
        • 2021-07-10
        • 2019-09-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多