-
-
Save insano10/a0dda1c10246860d9bfc1b345298c3f1 to your computer and use it in GitHub Desktop.
simple example showing string being coerced to a LocalDate in body params
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
; hit /string-to-date with body {"date-str": "2018-05-25"} on reitit 0.2.0 and you get 200 | |
; hit it with reitit 0.2.13 and you get 500 as coerced-date is still a string | |
(def ^:private invalid :clojure.spec.alpha/invalid) | |
(defn- local-date? | |
[date] | |
(try | |
(cond (string? date) (du/as-date date) | |
(instance? LocalDate date) date | |
:else invalid) | |
(catch Exception _ | |
invalid))) | |
(s/def ::local-date (s/conformer local-date? identity)) ;I know this is wrong to have unform as identity | |
(s/def ::date-str ::local-date) | |
(s/def ::string-to-date-body (s/keys :req-un [::date-str])) | |
(defn app [{:keys [] :as opts}] | |
(ring/ring-handler | |
(ring/router | |
[["/string-to-date" | |
{:post {:parameters {:body (s/spec ::string-to-date-body)} | |
:handler (fn [{{body :body} :parameters}] | |
(log/info body) | |
(log/info (type (:date-str body))) | |
(let [coerced-date (:date-str body)] | |
(if (= (type (jt/local-date)) (type coerced-date)) | |
(http/ok "its a LocalDate") | |
(http/internal-server-error (format "coerced type is %s" (type coerced-date))))))}}] | |
] | |
{:data {:coercion rcs/coercion | |
:muuntaja m/instance | |
:middleware [exception-middleware | |
params/wrap-params | |
muuntaja/format-negotiate-middleware | |
muuntaja/format-response-middleware | |
muuntaja/format-request-middleware | |
coercion/coerce-response-middleware | |
coercion/coerce-request-middleware]}}))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Are you sure this works? For me it only validates the date, it doesn't coerce it.