Skip to content

Commit

Permalink
Fixing strip-extra-keys-transformer for recursive map encoding
Browse files Browse the repository at this point in the history
  • Loading branch information
tomasd committed Sep 26, 2023
1 parent e7ed7b0 commit d02168f
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 9 deletions.
16 changes: 9 additions & 7 deletions src/malli/transform.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -381,16 +381,18 @@
(if (and (map? x) (not default-schema))
(reduce-kv (fn [acc k _] (if-not (ks k) (dissoc acc k) acc)) x x)
x))))))}
strip-map-of {:compile (fn [schema options]
(let [entry-schema (m/into-schema :tuple nil (m/children schema) options)
valid? (m/validator entry-schema options)]
{:leave (fn [x] (reduce (fn [acc entry]
strip-map-of (fn [stage]
{:compile (fn [schema options]
(let [entry-schema (m/into-schema :tuple nil (m/children schema) options)
valid? (m/validator entry-schema options)]
{stage (fn [x]
(reduce (fn [acc entry]
(if (valid? entry)
(apply assoc acc entry)
acc)) (empty x) x))}))}]
acc)) (empty x) x))}))})]
(transformer
{:decoders {:map strip-map, :map-of strip-map-of}
:encoders {:map strip-map, :map-of strip-map-of}}))))
{:decoders {:map strip-map, :map-of (strip-map-of :leave)}
:encoders {:map strip-map, :map-of (strip-map-of :enter)}}))))

(defn key-transformer [{:keys [decode encode types] :or {types #{:map}}}]
(let [transform (fn [f stage] (when f {stage (-transform-map-keys f)}))]
Expand Down
27 changes: 25 additions & 2 deletions test/malli/transform_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -414,10 +414,33 @@
(is (= {:x :kikka} (m/decode [:map [:x keyword?]] {:x "kikka", :y "kukka"} strict-json-transformer))))
(testing "encode"
(is (= "kikka" (m/encode keyword? :kikka strict-json-transformer)))
(is (= {:x "kikka"} (m/encode [:map [:x keyword?]] {:x :kikka, :y :kukka} strict-json-transformer)))))
(is (= {:x "kikka"} (m/encode [:map [:x keyword?]] {:x :kikka, :y :kukka} strict-json-transformer)))

(testing "nested map encode"
(is (= {:x {:a {:b {}}}}
(m/encode [:map
[:x [:map
[:a [:map [:b [:map]]]]]]]
{:x {:a {:b {}
:c {}}}
:additional 1}
strict-json-transformer))))

(testing "recursive map encode"
(is (= {:x {"a" {"b" {}}}}
(m/encode [:map {:registry {::kw-map [:map-of :keyword [:ref ::kw-map]]}}
[:x [:ref ::kw-map]]]

{:x {:a {:b {}
;; TODO: Additional invalid param invalidates the recursive map
;;"c" {}
}}
:additional 1}
strict-json-transformer
))))))

(let [transformer (mt/transformer
(mt/key-transformer
(mt/key-transformer
{:decode #(-> % (subs 4) keyword)
:encode #(->> % name (str "key_"))})
(mt/string-transformer)
Expand Down

0 comments on commit d02168f

Please sign in to comment.