schema

RAJKUMAR 2024-01-02T23:27:06.415559Z

Hi, I'm trying to simulate oneOf which is in JsonSchema in plumatic/Schema

imre 2024-01-03T11:57:12.631399Z

s/enum is applied incorrectly in the example, its correct application would be (s/defschema Animal (s/enum Dog Cat))

imre 2024-01-03T11:58:04.265109Z

However that won't help in this case - checking enum's docstring:

schema.core/enum [& vs]  A value that must be = to some element of vs.

imre 2024-01-03T11:59:12.955979Z

You'd need to use s/conditional:

(s/defschema Animal (s/conditional (every-pred map? #(contains? % :name)) Cat :else Dog))

(s/check Animal {:food "biscuits" :activities "running"})
=> nil
(s/check Animal {:name "Misty"})
=> nil

imre 2024-01-03T12:00:59.439389Z

(there are also a few other similar options: s/cond-pre could be used if the type of the datums were different (but here both Dog and Cat are maps). There's also s/either but that's deprecated due to it not working good with coercion, so s/conditional is suggested in its docstring

RAJKUMAR 2024-01-02T23:27:47.559019Z

example code here

RAJKUMAR 2024-01-02T23:27:52.956229Z

(s/defschema Dog
  {
   :food s/Str
   :activities s/Str
   })

(s/defschema Cat
  {
   :name s/Str
   })

(s/defschema Animal { s/enum [Dog Cat]}) 

RAJKUMAR 2024-01-02T23:28:09.175659Z

then (s/check Animal {:food "biscuits" :activities "running"}) gives error

RAJKUMAR 2024-01-02T23:28:24.005149Z

> Execution error at schema.core/parse-sequence-schema (core.cljc:940). > [{:food java.lang.String, :activities java.lang.String} {:name java.lang.String}] is not a valid sequence schema; a valid sequence schema consists of zero or more one elements, followed by zero or more optional elements, followed by an optional schema that will match the remaining elements.

RAJKUMAR 2024-01-02T23:28:49.057539Z

Any idea what is that I'm doing wrong here?