Skip to content

Commit

Permalink
Conditionally define coerce-map-indicating-invalidity
Browse files Browse the repository at this point in the history
  • Loading branch information
thumbnail committed Sep 19, 2022
1 parent 0b364d5 commit 043c491
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 13 deletions.
28 changes: 15 additions & 13 deletions src/nedap/utils/spec/api.cljc
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
(ns nedap.utils.spec.api
(:require
#?(:clj [clojure.spec.alpha :as spec] :cljs [cljs.spec.alpha :as spec])
[nedap.utils.spec.impl.check])
[nedap.utils.spec.impl.check]
[nedap.utils.spec.impl.spec-coerce :refer [spec-coerce-available?]])
#?(:cljs (:require-macros [nedap.utils.spec.api :refer [check!]])))

#?(:clj
Expand All @@ -15,16 +16,17 @@
{:pre [(-> args count even?)]}
`(nedap.utils.spec.impl.check/check! ~@args)))

(defn coerce-map-indicating-invalidity
"Tries to coerce the map `m` according to spec `spec`.
(when (spec-coerce-available?)
(defn coerce-map-indicating-invalidity
"Tries to coerce the map `m` according to spec `spec`.
If the coercion isn't possible, `::invalid? true` is associated to the map."
[spec m]
;; Very important: specs must be passed as keywords or symbols,
;; but never 'inline' as any other kind of objects.
;; Else spec-coerce will fail to coerce things.
{:pre [(check! qualified-ident? spec
map? m)]}
(let [m ((requiring-resolve 'spec-coerce.core/coerce) spec m)]
(cond-> m
(not (spec/valid? spec m)) (assoc ::invalid? true))))
If the coercion isn't possible, `::invalid? true` is associated to the map."
[spec m]
;; Very important: specs must be passed as keywords or symbols,
;; but never 'inline' as any other kind of objects.
;; Else spec-coerce will fail to coerce things.
{:pre [(check! qualified-ident? spec
map? m)]}
(let [m (spec-coerce.core/coerce spec m)]
(cond-> m
(not (spec/valid? spec m)) (assoc ::invalid? true)))))
8 changes: 8 additions & 0 deletions src/nedap/utils/spec/impl/spec_coerce.cljc
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
(ns nedap.utils.spec.impl.spec-coerce)

(defn spec-coerce-available? []
(try
(require 'spec-coerce.core)
true
(catch Exception _
false)))

0 comments on commit 043c491

Please sign in to comment.