Fork me on GitHub
#ring-swagger
<
2015-12-11
>
timgilbert14:12:25

Hi @juhoteperi... I got a little farther with that, but I'm a bit confused by how I access the actual data that is being considered for coercion in my (foo s) function - ideally I'd have a way to access the ["company" 49] bit of the incoming JSON

juhoteperi15:12:03

the matcher takes a schema as argument and returns a function, if schema is one that matcher wants to coerce, which takes in the value and returns either original or coerced value

timgilbert15:12:17

Oh, I see. So I'm returning a function from data->data-which-matches-the-schema?

juhoteperi15:12:57

Pretty much, but if the value is one that matcher can't handle, you can just return the original data

timgilbert15:12:09

Ok, gotcha. Thanks!

ikitommi18:12:52

pluggable coercion is not the simplest thing around, but the tests should give nice intro: https://github.com/metosin/compojure-api/blob/master/test/compojure/api/coercion_test.clj

timgilbert20:12:15

I got it more or less working, thanks for the help! I'm planning to write a little blog post about it for my company's tech blog at some point, but the gist of it was more or less this:

timgilbert20:12:20

(defn descriptor-decode
  "When the descriptor we're attempting to match is a descriptor schema, we try to convert its
  first element from a String to a Keyword. If the resulting data structure matches the general
  Descriptor schema, then we return it (so the value is coerced)."
  [sc]
  (when (re-matches #"^.*Descriptor$" (str (s/schema-name sc)))
    (fn [data]
      (if-not (sequential? data)
        data
        (let [coercion-attempt (into [(-> data first keyword)] (rest data))]
          (if (nil? (s/check ds/Descriptor coercion-attempt))
            coercion-attempt
            data))))))

(defn descriptor-dispatch [sc]
  (or (descriptor-decode sc)
      (rsc/json-schema-coercion-matcher sc)))

timgilbert20:12:20

I'm planning on just tagging the relevant schemas with metadata in the future instead of regex-matching on the name which seems kind of dumb, but that code does actually work

timgilbert20:12:25

...where ds/Descriptor is a conditional schema that's sort of a supertype of eg ProductDescriptor and ManufacturerDescriptor