metosin / spec-tools

Clojure(Script) tools for clojure.spec

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

(json-schema) How can we specify leaf fields's default value for nested objects?

iku000888 opened this issue · comments

Sorry if it is a noob question.

Say we have this existing spec

(s/def ::foo integer?)

(s/def ::bar string?)

(s/def ::foobar
  (s/keys
   :req-un
   [::foo]
   :opt-un
   [::bar]))

(s/def ::baz (s/keys :req-un [::foobar]))

And we want to specify that the foo field has a default 42, and bar field has a default "" so we get this, by modifying the above.

(json-schema/transform
 (st/spec {:spec ::baz}))
=>
;;desired output
{:type "object",
 :properties
 {"foobar"
  {:type "object",
   ;; Would like the deafault keys to be present, but directly rendering the above does not include it.
   :properties {"foo" {:type "integer" :default 42}, "bar" {:type "string" :default ""}},
   :required ["foo"],
   :title "some-ns/foobar"}},
 :required ["foobar"],
 :title "some-ns/baz"}

I am having trouble grasping how one can sneak in the :json-schema/default keys in.

Thanks in advance and I am grateful this project exists!

all keys with json-schema namespace will be merged into the generated result:

(s/def ::foo
  (st/spec
    {:spec integer?
     :json-schema/default 42}))

(s/def ::bar
  (st/spec
    {:spec string?
     :json-schema/default ""}))

(json-schema/transform
  (s/keys :req-un [::foo]
          :opt-un [::bar]))
;{:type "object",
; :properties {"foo" {:type "integer", :title "user/foo", :default 42},
;              "bar" {:type "string", :title "user/bar", :default ""}},
; :required ["foo"]}

@ikitommi Thanks! (and wow that was fast!)
So wrapping the s/def with (st/spec) is the way to go.
If there are other ways it would be great to know, but I can now start living life 😄