Skip to content

Commit

Permalink
Merge pull request #951 from metosin/fix-enum-encode
Browse files Browse the repository at this point in the history
Use type inferrer when encoding enums
  • Loading branch information
ikitommi authored Sep 7, 2023
2 parents 38d77ea + 06f4a4d commit 3f53fda
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 13 deletions.
24 changes: 16 additions & 8 deletions src/malli/transform.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -189,11 +189,17 @@
(set? x) (seq x)
:else x))

(defn -infer-child-decoder-compiler [schema _]
(-> schema (m/children) (m/-infer) {:keyword -string->keyword
:symbol -string->symbol
:int -string->long
:double -string->double}))
(defn -infer-child-compiler [method]
(fn [schema _]
(some-> schema
(m/children)
(m/-infer)
{:keyword {:decode -string->keyword
:encode m/-keyword->string}
:symbol {:decode -string->symbol}
:int {:decode -string->long}
:double {:decode -string->double}}
(method -any->string))))

;;
;; decoders
Expand All @@ -216,8 +222,8 @@
'double? -number->double
'inst? -string->date

:enum {:compile -infer-child-decoder-compiler}
:= {:compile -infer-child-decoder-compiler}
:enum {:compile (-infer-child-compiler :decode)}
:= {:compile (-infer-child-compiler :decode)}

:double -number->double
:keyword -string->keyword
Expand All @@ -239,6 +245,9 @@

'uuid? -any->string

:enum {:compile (-infer-child-compiler :encode)}
:= {:compile (-infer-child-compiler :encode)}

:keyword m/-keyword->string
:symbol -any->string
:qualified-keyword m/-keyword->string
Expand Down Expand Up @@ -301,7 +310,6 @@
:>= -any->string
:< -any->string
:<= -any->string
:= -any->string
:not= -any->string

'double -any->string}))
Expand Down
17 changes: 12 additions & 5 deletions test/malli/transform_test.cljc
Original file line number Diff line number Diff line change
Expand Up @@ -1039,8 +1039,15 @@
:equals2 'kikka
:equals3 1
:equals4 1.1}]
(testing "is not enabled by default"
(is (= value (m/decode schema value nil))))
(testing "works with json and string transformers"
(is (= expected (m/decode schema value (mt/json-transformer))))
(is (= expected (m/decode schema value (mt/string-transformer)))))))
(testing "decoding"
(testing "is not enabled by default"
(is (= value (m/decode schema value nil))))
(testing "works with json and string transformers"
(is (= expected (m/decode schema value (mt/json-transformer))))
(is (= expected (m/decode schema value (mt/string-transformer))))))
(testing "encoding"
(testing "is not enabled by default"
(is (= expected (m/encode schema expected nil))))
(testing "works with json and string transformers"
(is (= value (m/encode schema expected (mt/json-transformer))))
(is (= value (m/encode schema expected (mt/string-transformer))))))))

0 comments on commit 3f53fda

Please sign in to comment.