Skip to content

Commit

Permalink
Merge pull request #1045 from metosin/json-schema-definitions-path
Browse files Browse the repository at this point in the history
feat: allow changing prefix of json-schema $refs
  • Loading branch information
opqdonut authored Apr 19, 2024
2 parents 7a9df8e + f2c963a commit 0d8346a
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
6 changes: 4 additions & 2 deletions src/malli/json_schema.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,9 @@
(defprotocol JsonSchema
(-accept [this children options] "transforms schema to JSON Schema"))

(defn -ref [schema {::keys [transform definitions] :as options}]
(defn -ref [schema {::keys [transform definitions definitions-path]
:or {definitions-path "#/definitions/"}
:as options}]
(let [ref (as-> (m/-ref schema) $
(cond (var? $) (let [{:keys [ns name]} (meta $)]
(str (symbol (str ns) (str name))))
Expand All @@ -19,7 +21,7 @@
(swap! definitions assoc ref ::recursion-stopper)
(swap! definitions assoc ref (transform child options))))
;; '/' must be encoded as '~1' in JSON Schema - https://www.rfc-editor.org/rfc/rfc6901
{:$ref (apply str "#/definitions/" (str/replace ref #"/" "~1"))}))
{:$ref (apply str definitions-path (str/replace ref #"/" "~1"))}))

(defn -schema [schema {::keys [transform] :as options}]
(if (m/-ref schema)
Expand Down
10 changes: 9 additions & 1 deletion test/malli/json_schema_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -295,7 +295,15 @@
(testing "circular definitions are not created for closed schemas"
(is (= {:$ref "#/definitions/Foo", :definitions {"Foo" {:type "integer"}}}
(json-schema/transform
(mu/closed-schema [:schema {:registry {"Foo" :int}} "Foo"]))))))
(mu/closed-schema [:schema {:registry {"Foo" :int}} "Foo"])))))
(testing "definition path can be changed"
(is (= {:type "object"
:properties {:foo {:$ref "#/foo/bar/Foo"}}
:required [:foo]
:definitions {"Foo" {:type "integer"}}}
(json-schema/transform
[:schema {:registry {"Foo" :int}} [:map [:foo "Foo"]]]
{:malli.json-schema/definitions-path "#/foo/bar/"})))))

(deftest mutual-recursion-test
(is (= {:$ref "#/definitions/Foo"
Expand Down

0 comments on commit 0d8346a

Please sign in to comment.