2

我很喜欢和clojure.spec; 它有助于发现更接近原因的数据错误。目前我正在使用它来验证对 Web 服务器请求的响应,但是我在 clojure.spec 操作的语法上遇到了困难,该操作将允许两个不同的地图结构响应。

在我的数据中,Web 服务器请求有两种可能的响应:

{:assignment "1232123"}

{:no-more-assignments true}

我可以使用multi-spec,但这对于一些简单的事情来说似乎很冗长,例如为每种情况都有一个规范并将规范定义为:

(s/def ::response
  (s/or ::case-1 ::case-2))

是否有一些我忽略或需要使用的语法multi-spec

4

1 回答 1

7

您可以使用和or规格:andkeys

(s/def ::assignment string?)
(s/def ::no-more-assignments boolean?)
(s/def ::response
  (s/keys :req-un [(or ::assignment ::no-more-assignments)]))

(s/explain ::response {:assignment "123"})
;; Success!
(s/explain ::response {:foo true})
;; val: {:foo true} fails spec: :sandbox.so/response predicate: (or (contains? % :assignment) (contains? % :no-more-assignments))
于 2018-05-06T18:30:43.107 回答