From 134ff69e0a2ee7c1781b827a7fb2584a9a1ac3b8 Mon Sep 17 00:00:00 2001 From: Tommi Reiman Date: Tue, 14 Jul 2020 11:45:07 +0300 Subject: [PATCH] fix key-transformer --- src/malli/transform.cljc | 8 ++++---- test/malli/transform_test.cljc | 15 ++++++++++++++- 2 files changed, 18 insertions(+), 5 deletions(-) diff --git a/src/malli/transform.cljc b/src/malli/transform.cljc index 80e2b81be..f45aa6050 100644 --- a/src/malli/transform.cljc +++ b/src/malli/transform.cljc @@ -303,16 +303,16 @@ :encoders {:map transform}})))) (defn key-transformer [{:keys [decode encode]}] - (let [transform (fn [f] - (if f {:leave (fn [x] + (let [transform (fn [f stage] + (if f {stage (fn [x] (if (map? x) (reduce-kv (fn [m k v] (assoc m (f k) v)) (empty x) x) x))}))] (transformer - {:decoders {:map (transform decode)} - :encoders {:map (transform encode)}}))) + {:decoders {:map (transform decode :enter)} + :encoders {:map (transform encode :leave)}}))) (defn default-value-transformer [] (let [get-default (fn [schema] (some-> schema m/properties :default)) diff --git a/test/malli/transform_test.cljc b/test/malli/transform_test.cljc index b8a610999..64efaa4da 100644 --- a/test/malli/transform_test.cljc +++ b/test/malli/transform_test.cljc @@ -283,7 +283,20 @@ (is (= {"x_key" 18 "y_key" "john" "a_key" "doe"} (m/encode [:map [:x int?] [:y string?] [[:opt :z] boolean?]] {:x 18 :y "john" :a "doe"} - key-transformer)))))) + key-transformer))))) + + (testing "from strings and back" + (let [schema [:map + [:id :string] + [:github-followers pos-int?]] + transformer (mt/transformer + (mt/key-transformer {:decode keyword, :encode name}) + (mt/string-transformer)) + value {"id" "123", "github-followers" "10"}] + (is (= {:id "123", :github-followers 10} + (as-> value $ (m/decode schema $ transformer)))) + (is (= value + (as-> value $ (m/decode schema $ transformer) (m/encode schema $ transformer))))))) (deftest interceptor-style-transformers (testing "map"