This page is not created by, affiliated with, or supported by Slack Technologies, Inc.
2020-11-12
Channels
- # announcements (1)
- # architecture (112)
- # asami (22)
- # babashka (74)
- # beginners (189)
- # chlorine-clover (4)
- # cider (105)
- # clj-kondo (21)
- # clojure (45)
- # clojure-australia (1)
- # clojure-europe (26)
- # clojure-losangeles (4)
- # clojure-nl (3)
- # clojure-spec (5)
- # clojure-uk (8)
- # clojurescript (16)
- # conjure (1)
- # cursive (29)
- # datascript (21)
- # datomic (35)
- # events (1)
- # fulcro (12)
- # graalvm (3)
- # graphql (31)
- # kaocha (13)
- # malli (14)
- # meander (3)
- # mount (3)
- # off-topic (73)
- # pathom (9)
- # pedestal (5)
- # portal (2)
- # re-frame (4)
- # reagent (8)
- # reitit (3)
- # rum (1)
- # shadow-cljs (26)
- # spacemacs (3)
- # sql (6)
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"]
?@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?@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!