I'm trying to use https://github.com/metosin/malli?tab=readme-ov-file#malliexperimentaltime
Here is what I have
(ns foobar.core
(:require [malli.core :as m]
[malli.registry :as mr]
[malli.experimental.time :as met]))
;; This should add the malli.experimental.time schemas
(mr/set-default-registry!
(mr/composite-registry
(m/default-schemas)
(met/schemas)))
So, I would expect one of those things to be truthy, but none is:
(m/validate :time/local-date "2024-01-01")
(m/validate [:time/local-date] "2024-01-01")
(m/validate [:time/local-date {:pattern "yyyy-mm-dd"}] "2024-01-01")
(m/validate [:time/local-date {:pattern "yyyy-MM-dd"}] "2024-01-01")
(m/validate [:time/local-date {:pattern "YYYY-MM-DD"}] "2024-01-01")
What am I missing here ?
The doc also mentions a "transformation" feature, is that required here ? https://github.com/metosin/malli?tab=readme-ov-file#transformation---malliexperimentaltimetransform
Thanks to @gwang-jim-kim for the help, but I found at what I was missing:
I was confusing the role of m/validate
, m/decode
and m/coerce
m/validate
check that a value conforms to a schemam/decode
will use a transformer to turn a value into something conforming to the schema, but silently failm/coerce
will do the same, but raiseIn my case, I want to turn the input string into a date, so I was needing m/coerce
There are already built-in transformers to pass to m/coerce
in the malli.experimental.time.transformer
namespace
However, for some reason, my project was depending on org.clojure/clojure "1.10.1"
, and this caused an error when loading the workspace (because math
was not available.)
(This is fixed by depending on more recent version (eg "1.11.1"))
Also, I was using the wrong parsing pattern sometimes :facepalm:...
So, in the end, this does what I want:
(ns flight.core
(:require [malli.core :as m]
[malli.registry :as mr]
[malli.experimental.time :as met]
[malli.experimental.time.transform :as mett]))
(mr/set-default-registry!
(mr/composite-registry
(m/default-schemas)
(met/schemas)))
(def schema [:time/local-date {:pattern "yyyy-MM-dd"}] )
(m/validate schema "2024-01-01") ;;=> false, the string is not a LocalDate
(m/coerce schema "2024-01-01" mett/time-transformer) ;;=> this returns a java.time.LocalDate
(m/decode schema "2024-01-01x" mett/time-transformer) ;;=> this returns the string "2024-01-01x" because decode silently ignores transformation that raise error
(m/coerce schema "2024-01-01x" mett/time-transformer) ;;=> this raises an error
(m/validate schema (m/decode schema "2024-01-01x" mett/time-transformer)) ;;=> this returns false
(m/validate schema (m/decode schema "2024-01-01" mett/time-transformer)) ;;=> this returns true