Fork me on GitHub
#reitit
<
2020-11-12
>
malesch16:11:05

Hi all I am trying to get a better grasp of parameter coercion with Malli and want to perform some more advanced coercion. For instance a query parameter colors which takes a comma-separated list of values. I am looking for a schema which could validate and coerce the values into a set. Is this possible (or advisable at all 😉)? I am playing around with this but did not succeed so far:

(require '[malli.core :as m])
(require '[malli.error :as me])
(require '[malli.transform :as mt])

(def params {:colors "CEA4B9,FFE8C0,AB0318"})                  ; e.g. from a request
(def invalid-colors-params {:colors "CEG4B9,FFE8C0,A0318"})    ; with invalid color values: CEG4B9, A0318
(def expected-result {:colors #{"CEA4B9" "FFE8C0" "AB0318"}})

(def color-value [:re {:error/fn (fn [{:keys [value]} _] (format "Not a valid color code: %s" value))} #"[0-9a-fA-F]{6}"])
(def colors [:map
             [:colors [:set {:error/message "Invalid colors parameter"
                             :decode/string (fn [s] (some-> s (clojure.string/split #",") set))
                             :encode/string (fn [cs] (apply str (interpose "," cs)))}
                        color-value]]])
(->> "ABCDEF" (m/explain color-value) me/humanize)
;=> nil

(->> "ABCDEg" (m/explain color-value) me/humanize)
;=> ["Not a valid color code: abcdeG"]

(m/decode colors params mt/string-transformer)
;=> {:colors #{"AB0318" "FFE8C0" "CEA4B9"}}

(m/encode colors expected-result mt/string-transformer)
;=> {:colors "AB0318,FFE8C0,CEA4B9"}
Is it possible to get an error explanation for coercion invalid-colors-param and something like ["Not a valid color code: CEG4B9" "Not a valid color code: A0318"]?

ikitommi17:11:01

@malesch the current:

(as-> invalid-colors-params $
      (m/decode colors $ mt/string-transformer)
      (m/explain colors $)
      (me/humanize $))
{:colors #{["Not a valid color code: CEG4B9"] ["Not a valid color code: A0318"]}}
is not ok, what would be an expected result?

3
malesch18:11:04

@ikitommi Thanks for the quick response (event from your 🌴!!), everyhing is obviously fine. The internal exception I got when adding above schema to my handler has an other cause and not being very familiar with Malli let me believe that I basically did something wrong with the schema definition 😊. Thanks again!