Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Compile spec coercers #167

Open
ikitommi opened this issue Feb 20, 2019 · 0 comments
Open

Compile spec coercers #167

ikitommi opened this issue Feb 20, 2019 · 0 comments

Comments

@ikitommi
Copy link
Member

ikitommi commented Feb 20, 2019

Spec are walked at runtime with st/coerce. As the specs SHOULD NOT CHANGE in production, we can precompile the coercers for faster processing.

With the given specs:

(require '[clojure.spec.alpha :as s])
(require '[spec-tools.core :as st])

(s/def :sku/id keyword?)
(s/def ::sku (s/keys :req-un [:sku/id]))
(s/def ::skus (s/coll-of ::sku :into []))

(s/def :photo/id int?)
(s/def ::photo (s/keys :req-un [:photo/id]))
(s/def ::photos (s/coll-of ::photo :into []))

(s/def ::data (s/keys :req-un [::skus ::photos]))

Compile coercers:

(def string->data (st/coercer ::data st/string-transformer))
(def json->data (st/coercer ::data st/json-transformer))

Apply them:

(string->data
  {:skus [{:id "123"}]
   :photos [{:id "123"}]})
; {:skus [{:id :123}]
;  :photos [{:id 123}]}
(json->data
  {:skus [{:id "123"}]
   :photos [{:id "123"}]})
; {:skus [{:id :123}]
;  :photos [{:id "123"}]}

Maybe even:

(let [[string->data json->data] (st/coercers ::data [st/string-transformer st/json-transformer]))]
     ....)

Caveat: spec registration is imperative, one can re-register any spec at any time, so the compiled results can be out-dated. Such is life in the land of lisp.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant