Fork me on GitHub
#clojure-spec
<
2018-09-14
>
lilactown15:09:13

how would I represent a constraint on two related fields? e.g.:

{:type :type/json
 :cardinality :cardinality/many} ;; invalid! :cardinality/many can only be used with :type/string and :type/ref

dominicm15:09:03

@lilactown use a predicate on the map?

lilactown15:09:06

right.... keep thinking of specs at the key level. thanks

Spencer Apple17:09:59

Hello, is it possible to include external data when using spec to validate data - or would a separate function be better? E.G. validating an api response, and using a key from the request (such as the length of the pagination to validate the number of values returned).

dadair17:09:33

Could you define a spec that is the combination of the request + the response (i.e., the context), and then use a predicate to check the mentioned constraints?

dadair17:09:06

something like the following?

(s/def ::request ,,)
(s/def ::response ,,)
(s/def ::context
  (s/and (s/keys :req [::request ::response])
         #(= (-> % ::request :pagination :length) (count (-> % ::response :values)))))

Alex Miller (Clojure team)17:09:13

I think the question is whether that’s better than just writing the equivalent Clojure code

Alex Miller (Clojure team)17:09:26

(I tend to think not in this case)

Spencer Apple17:09:28

hmm @dadair that is a really good example, and I think it would work. Thanks for writing that out. I was curious about if it made sense to include in the spec - and I kind of think the length of a vector is part of the data shape… but perhaps it still doesn’t fit in the spec

Spencer Apple17:09:45

I will eventually get to the data generation side of this spec, in which I will want to include the :pagination :length parameter from the request to generate the correct length of ::response ::values. At that point I might need to combine the ::request and ::response specs?

Alex Miller (Clojure team)18:09:35

yes, if you want to generate one thing, they need to be in the same spec, although I’m not sure why you need to generate responses (presumably your code is making those)

Spencer Apple18:09:50

Gotcha, and thanks for you responses! The request and response are to and from an external API. I want to generate responses to test our data munging flows. Since the data munging fns rely on the request parameters, the generated responses also have to conform (at least partially) to the requests that “generated them”.

Alex Miller (Clojure team)19:09:03

gotcha, that makes sense

Alex Miller (Clojure team)19:09:40

depending how much stuff there is, you might able to gen both independently, then just copy values that have to match from the request into the response or something like that

Spencer Apple20:09:21

ah interesting idea!