07: spec gen customization and omission
You can override the values produces by ent-db-spec-gen in the query:
1
(ns reifyhealth.specmonstah-tutorial.07
2
(:require [reifyhealth.specmonstah.core :as sm]
3
[loom.io :as lio]
4
[clojure.spec.alpha :as s]
5
[reifyhealth.specmonstah.spec-gen :as sg]))
6
7
(s/def ::id (s/and pos-int? #(< % 100)))
8
(s/def ::not-empty-string (s/and string? not-empty #(< (count %) 10)))
9
10
(s/def ::username ::not-empty-string)
11
(s/def ::user (s/keys :req-un [::id ::username]))
12
13
(s/def ::name ::not-empty-string)
14
(s/def ::topic (s/keys :req-un [::id ::name ::owner-id]))
15
16
(s/def ::owner-id ::id)
17
(s/def ::topic-id ::id)
18
(s/def ::content ::not-empty-string)
19
(s/def ::post (s/keys :req-un [::id ::owner-id ::topic-id ::content]))
20
21
(def schema
22
{:user {:prefix :u
23
:spec ::user}
24
:topic {:prefix :t
25
:spec ::topic
26
:relations {:owner-id [:user :id]}}
27
:post {:prefix :p
28
:spec ::post
29
:relations {:topic-id [:topic :id]}}})
30
31
(defn ex-01
32
[]
33
(sg/ent-db-spec-gen-attr {:schema schema}
34
{:user [[1 {:spec-gen {:username "barb"}}]]
35
:post [[1 {:spec-gen {:content "so good to be barb"}}]]}))
36
37
(ex-01)
38
;; =>
39
{:p0 {:id 81, :owner-id 96, :topic-id 68, :content "so good to be barb"}
40
:t0 {:id 68, :name "3l1IR8", :owner-id 3}
41
:u0 {:id 3, :username "barb"}}
Copied!
We're using the same specs and schema as in the last section. Things get interesting at line 34, where we have this query:
1
{:user [[1 {:spec-gen {:username "barb"}}]]
2
:post [[1 {:spec-gen {:content "so good to be barb"}}]]}
Copied!
In the refs section we saw that query terms could take an optional map. Here, the optional maps are {:spec-gen {:username "barb"}} and {:spec-gen {:content "so good to be barb"}} . When you include :spec-gen key, the associated map is merged into whatever value is generated by clojure.spec.
You can also specify that you don't want an ent to reference one of the ents defined in its schema. For example, if a :todo-list's :owner-id is optional and you don't want it to be present, you could do this:
1
(defn ex-02
2
[]
3
(sg/ent-db-spec-gen-attr {:schema schema}
4
{:topic [[1 {:refs {:owner-id ::sm/omit}}]]}))
5
(ex-02)
6
;; =>
7
{:t0 {:id 12, :name "418y13ST"}}
Copied!
::sm/omit prevents the referenced ent from even being created in the ent db. It's as if the :owner-id relation didn't exist in the schema. spec generation respects this and omits :owner-id from the map it generates. If you want the key :owner-id to be present with the value nil, you'd have to specify that like this:
1
(defn ex-03
2
[]
3
(sg/ent-db-spec-gen-attr {:schema schema}
4
{:topic [[1 {:refs {:owner-id ::sm/omit}
5
:spec-gen {:owner-id nil}}]]}))
6
7
(ex-03)
8
;; =>
9
{:t0 {:id 2, :name "pijm" :owner-id nil}}
Copied!
Last modified 2yr ago
Copy link