我希望能够为这些模式中的验证错误生成用户友好或指定自定义错误消息:
(def Uuid (s/constrained String #(re-matches #"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$" (name %))))
(def FirstName s/Str)
(def LastName s/Str)
(s/defschema Person {(s/required-key :id) Uuid,
(s/required-key :first-name) FirstName,
(s/required-key :last-name) LastName})
有效架构:
{
:uuid "e143499c-1257-41e4-b951-c9e586994ff9"
:first-name "john"
:last-name "smith"
}
架构无效:
{
:uuid ""
:first-name nil
:last-name nil
}
无效架构 - 错误:
{
"id" : "(not (app.person/fn--4881 \"\"))",
"first-name" : "(not (instance? java.lang.String nil))"
"last-name" : "(not (instance? java.lang.String nil))"
}
我希望能够为非程序员生成更具可读性的东西,例如:
{
"id" : "invalid uuid",
"first-name" : "must be a string"
"last-name" : "must be a string"
}
答案 0 :(得分:3)
有趣的是,几天前它已作为图书馆发布了。
请参阅:
https://github.com/siilisolutions/humanize
首先,您还需要标记Uuid
架构,以便以后可以匹配:
;; Note the last param I added:
(def Uuid (sc/constrained
String
#(re-matches #"^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$"
(name %))
'UUID))
(require '[schema.core :as sc]
'[humanize.schema :as hs])
(#'hs/explain (sc/check Person {:id "foo"
:first-name "foo"
:last-name 3})
(fn [x]
(clojure.core.match/match
x
['not ['UUID xx]]
(str xx " is not a valid UUID")
:else x)))
结果:
=> {:id "foo is not a valid UUID", :last-name "'3' is not a string but it should be."}
注意,它需要一个小技巧,因为hs/explain
很遗憾。