Skip to content

Instantly share code, notes, and snippets.

@ikitommi
Last active February 22, 2020 17:33
Show Gist options
  • Save ikitommi/87f9b9136167c6be2e4b9f315a212046 to your computer and use it in GitHub Desktop.
Save ikitommi/87f9b9136167c6be2e4b9f315a212046 to your computer and use it in GitHub Desktop.
spec select
;; a sample data
(def tappi
{:mydomain/type :restaurant
:mydomain.restaurant/name "Vanha Tappi"
:mydomain.restaurant/tags #{:burgers :beer}
:mydomain.restaurant/stars 4.5
:mydomain.restaurant/address {:mydomain.address/street "Jokipohjantie 18"
:mydomain.address/city "Tampere"}})
(require '[clojure.spec-alpha2 :as s])
(s/def :mydomain/type keyword?)
(s/def :mydomain.restaurant/name string?)
(s/def :mydomain.restaurant/tags (s/coll-of keyword? :kind set?))
(s/def :mydomain.restaurant/stars double?)
(s/def :mydomain.address/street string?)
(s/def :mydomain.address/city string?)
(s/def :mydomain.restaurant/address
(s/schema [:mydomain.address/street
:mydomain.address/city]))
(s/def :mydomain.restaurant/restaurant
(s/schema [:mydomain/type
:mydomain.restaurant/name
:mydomain.restaurant/tags
:mydomain.restaurant/stars
:mydomain.restaurant/address]))
;; select where :mydomain.restaurant/stars is not present
(def restaurant-select
(s/select
:mydomain.restaurant/restaurant
[:mydomain/type
:mydomain.restaurant/name
:mydomain.restaurant/tags
:mydomain.restaurant/address
{:mydomain.restaurant/address [:mydomain.address/street
:mydomain.address/city]}]))
;; no extra keys allowed here, e.g. border/api validation
(def restaurant-closed-keys
#{:mydomain.restaurant/restaurant
:mydomain.restaurant/address})
(s/valid?
restaurant-select
tappi
{:closed restaurant-closed-keys})
; => true
(s/valid?
restaurant-select
(dissoc tappi :mydomain.restaurant/stars)
{:closed restaurant-closed-keys})
; => true
;; select can't closed :(
(s/valid?
restaurant-select
(assoc tappi :EVIL "hacker)
{:closed restaurant-closed-keys})
; => true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment