Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Clojure spec coerce nested map value

I coerce a map value like so:

(require '[clojure.spec :as s])

(defn x-integer? [x]
  (cond
    (integer? x) x
    (string? x) (try
                  (Integer/parseInt x)
                  (catch Exception e
                    :clojure.spec/invalid))
    :else :clojure.spec/invalid))

(s/def ::port (s/conformer x-integer?))

(s/def ::config (s/keys :req [::port]))

(s/conform ::config {::port "12345"}) ;;=> #:my.ns{:port "12345"}

However I do not see how I could do the same with the following map instead :

(s/conform ::config {::nested-data {:port "12345"}}) ;;=> something like that maybe ? #:my.ns/nested-data{:port 12345}

How should ::config be defined ? Also, would it be preferable to have {::nested-data {::port "12345"}} instead ?

like image 493
nha Avatar asked Jul 17 '16 23:07

nha


1 Answers

(s/def ::port (s/conformer x-integer?))
(s/def ::nested-data (s/keys :req-un [::port]))
(s/def ::config (s/keys :req [::nested-data]))
(s/conform ::config {::nested-data {:port "12345"}})
;;=> #:spec.examples.guide{:nested-data {:port 12345}}
like image 184
Alex Miller Avatar answered Sep 28 '22 05:09

Alex Miller