2

我正在尝试使用 clojure.spec 和metosin/spec-tools来验证和符合我的应用程序中的数据。在阅读了规范工具文档后,我不清楚我应该如何包装我的规范,spec-tools.core/spec以便符合的数据没有额外的键(它适用于顶级地图,但不适用于内部结构的地图)。

一些有助于澄清问题的代码:

(ns prodimg.spec
  (:require [clojure.spec.alpha :as s]
            [spec-tools.core :as st]
            [spec-tools.spec :as st.spec]))

(def ^:private not-blank? #(and (string? %)
                                (not (clojure.string/blank? %))))

(s/def :db/id integer?)

(s/def :model.image/id :db/id)
(s/def :model.image/type not-blank?)
(s/def :model.image/product-id :db/id)

(s/def :model.product/id :db/id)
(s/def :model.product/parent-id (s/nilable :db/id))
(s/def :model.product/name not-blank?)
(s/def :model.product/description string?)
(s/def :model.product/price (s/nilable decimal?))

; ----- request specs -----

; create product

(s/def :req.product.create/images (s/* (s/keys :req-un [:model.image/type])))
(s/def :req.product.create/children
  (s/* (s/keys :req-un [:model.product/name :model.product/description]
               :opt-un [:model.product/price])))

(s/def :req.product/create
  (st/spec (s/keys :req-un [:model.product/name :model.product/description]
                   :opt-un [:model.product/price
                            :model.product/parent-id
                            :req.product.create/images
                            :req.product.create/children])))

现在假设我有以下要验证/符合的数据:

(def data {:name "Product"
           :description "Product description"
           :price (bigdec "399.49")
           :extra-key "something"
           :images [{:type "PNG" :extra-key "something else"}])

(st/conform :req.product/create data st/strip-extra-keys-conforming)
; below is the result
; {:name "Product"
   :description "Product description"
   :price 399.49M
   :images [{:type "PNG" :extra-key "something else"}]

我尝试更改:req.product.create/images声明以包括st/spec调用包装s/*表单或s/keys表单,或两者兼而有之,但更改并没有改变结果。

有什么想法可以解决这个问题吗?

4

1 回答 1

1

奇怪的是,最新版本[metosin/spec-tools "0.5.1"]发布于 2017-10-31 (所以在你的帖子之前),我唯一需要做的改变是按照部分Map conforming下的文档中的示例进行操作,这似乎是你已经尝试过的尝试之一:包装s/keys如下st/spec

改变

(s/def :req.product.create/images (s/* (s/keys :req-un [:model.image/type])))

(s/def :req.product.create/images (s/* (st/spec (s/keys :req-un [:model.image/type]))))

我得到了预期的输出:

(st/conform :req.product/create data st/strip-extra-keys-conforming)
=>
{:description "Product description",
 :images [{:type "PNG"}],
 :name "Product",
 :price 399.49M}
于 2018-02-15T21:30:12.627 回答