1

我在我的compojure-api中使用plumatic/schema来验证端点的输入。

我的架构中有两个键:Field1& Field2。我希望能够为我的模式定义一个规则,例如:

WHEN Field1 = "AA" 
THEN Field2 is required-key 
ELSE Field2 is optional-key

但是,我似乎只能将密钥设置为必需或可选。是否可以使密钥依赖于另一个密钥?

(schema/def Field1
  (schema/enum "AA" "BB"))

(schema/def Field2
  (schema/enum "AAAA" "BBBB" "CCCC"))


(schema/defschema MySchema
  {(schema/required-key :field1)           Field1
   
   ; Here I want some kind of logic to make the key required if 
   (if (= Field1 "AA")
       (schema/required-key :field2)      Field2
       (schema/optional-key :field)      Field2)
   })

4

1 回答 1

2
(use '[plumbing.core])

(schema/defschema MySchema
    (schema/conditional
        (fn-> :field1 (= "AA"))
        (schema/schema-with-name {(schema/required-key :field1) Field1
                                  (schema/required-key :field2) Field2} "cond1")
        
        :else
        (schema/schema-with-name {(schema/required-key :field1) Field1
                                        (schema/optional-key :field2) Field2} "cond2")))
于 2020-10-25T13:44:00.940 回答