From f2c963a170c40ea4ea51e33ea322d1841126f467 Mon Sep 17 00:00:00 2001 From: Joel Kaasinen Date: Fri, 19 Apr 2024 11:21:17 +0300 Subject: [PATCH] feat: allow changing prefix of json-schema $refs ... via option :malli.json-schema/definitions-path needed for metosin/reitit#616 --- src/malli/json_schema.cljc | 6 ++++-- test/malli/json_schema_test.cljc | 10 +++++++++- 2 files changed, 13 insertions(+), 3 deletions(-) diff --git a/src/malli/json_schema.cljc b/src/malli/json_schema.cljc index 74fa08653..07c52b681 100644 --- a/src/malli/json_schema.cljc +++ b/src/malli/json_schema.cljc @@ -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)))) @@ -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) diff --git a/test/malli/json_schema_test.cljc b/test/malli/json_schema_test.cljc index 4992a9309..873a02e04 100644 --- a/test/malli/json_schema_test.cljc +++ b/test/malli/json_schema_test.cljc @@ -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"