Skip to content

Instantly share code, notes, and snippets.

@jazzytomato
Last active April 21, 2017 17:27
Show Gist options
  • Save jazzytomato/3deb4b0bfa761808372aa56f6f0781f0 to your computer and use it in GitHub Desktop.
Save jazzytomato/3deb4b0bfa761808372aa56f6f0781f0 to your computer and use it in GitHub Desktop.
Ring middleware for parsing query params with clojure.spec
(defn wrap-query-params-spec [h]
"Try to parse query params with clojure spec. Look for a spec named like 'query-params/[uri]'
If found and the spec does not conform, return the explained message"
(fn [req]
(try
(let [query-spec-k (keyword (str "query-params" (:uri req)))
query-params (keywordize-keys (:query-params req))
conformed-query-params (s/conform query-spec-k query-params)]
(if (= :clojure.spec/invalid conformed-query-params)
(->
(response {:error-message (s/explain-str query-spec-k query-params)})
(status 422))
(h (assoc req :params conformed-query-params))))
(catch Exception e (h req)))))
;; Usage example, for a route like /coords
(s/def :query-params/coords (s/keys :req-un [:coords/lat :coords/lng]
:opt-un [:result/limit]))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment