Skip to content

Instantly share code, notes, and snippets.

@borkdude
Created August 10, 2020 08:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save borkdude/6b9c48636b5f9169d26deb13dcfc8ba9 to your computer and use it in GitHub Desktop.
Save borkdude/6b9c48636b5f9169d26deb13dcfc8ba9 to your computer and use it in GitHub Desktop.
Validating output from edamame with malli
{:deps {metosin/malli {:git/url "https://github.com/metosin/malli" :sha "230b1767729aad3e02568f1320855e2b45d2d9b5"}
borkdude/edamame {:git/url "https://github.com/borkdude/edamame" :sha "64c7eb43950eb500ba7429dded48257cd15355ae"}
}}
(ns edamalli.core
(:require [edamame.core :as e]
[malli.core :as m]
[malli.transform :as mt]))
(defrecord WrappedNum [obj loc])
(defn postprocess [{:keys [:obj :loc]}]
(if (number? obj) (->WrappedNum obj loc) obj))
(defn fail! [{:keys [:obj :loc]}]
(throw (ex-info (str "so bad " obj "/" loc) {})))
(def <42 [:and int? [:< 42]])
(def Schema [:tuple keyword? [:map {:encode/success :obj,
:encode/failure fail!} [:obj <42]]])
(def valid? (m/validator Schema))
(def success (m/encoder Schema (mt/transformer {:name :success})))
(def failure (m/encoder Schema (mt/transformer {:name :failure})))
(defn parse-validate-and-transform [s]
(let [x (e/parse-string s {:postprocess postprocess})]
(if (valid? x) (success x) (failure x))))
(defn -main [& _args]
(parse-validate-and-transform "[:foo 42]")
;; TODO:
;; - validate that the WrappedNum contains value < 42
;; - then transform it to only that number
;; - else raise error, printing the location metadata of that number
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment