棱镜模式强制 - 重命名映射键
Prismatic schema coercion - renaming map key
我正在尝试使用 prismatic-schema (1.0.4) 强制映射
我要胁迫
{:a 1}
至
{:b 1}
将自定义匹配器与架构一起使用:
{:b s/Int}
但是这段代码不起作用:
(require '[schema.core :as s])
(require '[schema.coerce :as coerce])
((coerce/coercer {:b s/Int}
(fn [s]
(when (= s s/Keyword)
(fn [x]
(if (= x :a)
:b
x)))))
{:a 1})
输出:
#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}}
我尝试通过 运行 以下代码进行调试,该代码匹配架构中的所有内容并输出当前值和匹配的架构:
((coerce/coercer {:b s/Int}
(fn [s]
(when true
(fn [x]
(println s x)
x))))
{:a 1})
输出:
{:b Int} {:a 1}
=>
#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}}
貌似匹配器一到地图就炸了?
Schema 首先将您的地图分解成与模式匹配的部分,然后将每个 MapEntry 强制转换为相应的 MapEntry 模式,依此类推。这种故障在你的情况下失败了,所以你永远不会找到关键。
要完成您想要的,您必须将强制转换附加到地图模式并使用例如clojure.set/rename-keys
在你的强制函数中:
(def Foo {:b s/Int})
((coerce/coercer
Foo
(fn [s]
(when (= s Foo)
#(clojure.set/rename-keys % {:a :b}))))
{:a 1})
我正在尝试使用 prismatic-schema (1.0.4) 强制映射
我要胁迫
{:a 1}
至
{:b 1}
将自定义匹配器与架构一起使用:
{:b s/Int}
但是这段代码不起作用:
(require '[schema.core :as s])
(require '[schema.coerce :as coerce])
((coerce/coercer {:b s/Int}
(fn [s]
(when (= s s/Keyword)
(fn [x]
(if (= x :a)
:b
x)))))
{:a 1})
输出:
#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}}
我尝试通过 运行 以下代码进行调试,该代码匹配架构中的所有内容并输出当前值和匹配的架构:
((coerce/coercer {:b s/Int}
(fn [s]
(when true
(fn [x]
(println s x)
x))))
{:a 1})
输出:
{:b Int} {:a 1}
=>
#schema.utils.ErrorContainer{:error {:b missing-required-key, :a disallowed-key}}
貌似匹配器一到地图就炸了?
Schema 首先将您的地图分解成与模式匹配的部分,然后将每个 MapEntry 强制转换为相应的 MapEntry 模式,依此类推。这种故障在你的情况下失败了,所以你永远不会找到关键。
要完成您想要的,您必须将强制转换附加到地图模式并使用例如clojure.set/rename-keys
在你的强制函数中:
(def Foo {:b s/Int})
((coerce/coercer
Foo
(fn [s]
(when (= s Foo)
#(clojure.set/rename-keys % {:a :b}))))
{:a 1})