Skip to content

Instantly share code, notes, and snippets.

@clyfe
Last active October 13, 2015 12:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save clyfe/b0d1ebfd99304f6e2a9c to your computer and use it in GitHub Desktop.
Save clyfe/b0d1ebfd99304f6e2a9c to your computer and use it in GitHub Desktop.
Allow arrays as nested values
;; Portions of this file are taken from the clj-http project.
;; https://github.com/dakrone/clj-http
;; They are licenced under MIT License.
(ns client.middleware
"clj-http 3.0.0 master is a bit in limbo, rather than fork it, or wait for the maintainer,
this namespace tries to make up for some of it's shorcomings.
See:
https://github.com/dakrone/clj-http/issues/170
https://github.com/dakrone/clj-http/pull/280
Once clj-http master is stable, this namespaces should be removed."
(:require [clj-http.client :as client]
[clojure.walk :refer [prewalk]]))
(defn- nest-kv
[kv]
(if (and (vector? kv)
(or (map? (second kv))
(vector? (second kv))))
(let [[fk m] kv]
(reduce-kv (fn [m sk v]
(assoc m
(str (name fk)
\[ (if (integer? sk) sk (name sk)) \])
v))
{}
m))
kv))
(defn- nest-params
[request param-key]
(if-let [params (request param-key)]
(assoc request param-key (prewalk nest-kv params))
request))
(defn wrap-nested-params
"Middleware wrapping nested parameters for query strings.
Supports vectors. Always nests on GET."
;; See https://github.com/dakrone/clj-http/commit/4044f8583e6956e0d7572de6077e552f1de118a1
[client]
(fn [{:keys [content-type request-method] :as req}]
(if (or (nil? content-type)
(= content-type :x-www-form-urlencoded)
(= request-method :get))
(client (reduce
nest-params
req
[:query-params :form-params]))
(client req))))
(def default-middleware
"The default list of middleware clj-http uses for wrapping requests,
with nest-params replaced with our implementation."
(replace {client/wrap-nested-params wrap-nested-params}
client/default-middleware))
(ns usage
(:require [clj-http.client :as client]
[client.middleware :as m])))
(defn request [req]
(client/with-middleware m/default-middleware
(client/request req)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment