Fork me on GitHub
#malli
<
2021-04-06
>
ribelo16:04:21

Is it possible to create a key in a map using decode?

ribelo16:04:21

something like {:a 1 :b 2} => {:c 3}

nilern17:04:54

Sure it is

nilern17:04:58

(m/decode [:map {:decode/abc (fn [m]
                               (if (and (map? m) (contains? m :a) (contains? m :b))
                                 (-> m
                                     (dissoc :a :b)
                                     (assoc :c (+ (:a m) (:b m))))
                                 m))}
           [:a :int] [:b :int]]
          {:a 1, :b 2}
          (mt/transformer {:name :abc}))
=> {:c 3}

nilern17:04:20

https://github.com/metosin/malli#value-transformation does have this info although the explanations are a bit sparse

ribelo18:04:14

I've read it, but somehow it didn't occur to me that I could use decode/encode on the whole map and not on an individual key

nilern18:04:05

Yes that is the "key" to changing keys :drum_with_drumsticks:

ikitommi18:04:20

👍 small nitpick: the example could be encode as it transforms the value out of schema. Or the schema should not require :a & :b as they are not in the result.

👍 1