plumatic / schema

Clojure(Script) library for declarative data description and validation
Other
2.4k stars 256 forks source link

Feature suggestion: s/matches? #331

Closed gfredericks closed 8 years ago

gfredericks commented 8 years ago

Most of the time that I find myself using s/check it's because I want to know if something matches or not.

(def matches? (complement check))

Just a moment ago I wrote this and realized how much more readable it could be and thought I should at least suggest adding matches?:

(condp #(not (s/check %1 %2)) x
  schema-1
  ...

  schema-2
  ...)
w01fe commented 8 years ago

Thanks for the suggestion! I'm open to adding this, but would be curious to hear a bit more about your use case. I don't think I've run into any use cases where I just wanted to test matching and didn't care about the error message on failure (or performance, which mandates creating a checker up front).

Thanks again!

gfredericks commented 8 years ago

It most recently came up with using my schema-bijections library to handle a situation like this:

(s/defn specific-function-A
  [arg :- ThingA]
  ...)

(s/defn specific-function-B
  [arg :- ThingB]
  ...)

(s/defn general-function
  [arg :- MoreGenericSchemaJSON]
  (condp #(nil? (matches? %1 %2)) arg
     ThingAJSON
     (-> arg schemas/ThingA<-JSON specific-function-A)

     ThingBJSON
     (-> arg schemas/ThingB<-JSON specific-function-B)

     (throw (ex-info "Didn't match any schema!" {:arg arg}))))

Though in fairness the lack of schema error info in that last line did cause me to refactor this into a cond-schema macro that collects all the schema errors and throws the shortest one. So heck maybe it really is a bad idea. ☺

w01fe commented 8 years ago

Thanks for the details, that's really helpful. As I mentioned we're open to adding this if there's a good use case, so please feel free to reopen later.