Skip to content

allow nested array query params #629

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: 3.x
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 23 additions & 11 deletions src/clj_http/client.clj
Original file line number Diff line number Diff line change
Expand Up @@ -965,20 +965,32 @@
([req respnd raise]
(client (form-params-request req) respnd raise))))

(defn- subscript [k i]
(str (name k) \[ i \]))

(defn- unnest-1 [param-assoc]
(mapcat (fn [[k v]]
(if (sequential? v)
(map-indexed (fn [i sv] [(subscript k (str i)) sv]) v)
(map (fn [[i sv]] [(subscript k (name i)) sv]) (seq v))))
param-assoc))

(defn- unnest-inner [param-assoc]
(let [{nested true flat false} (group-by (comp coll? second) param-assoc)]
(if (empty? nested)
param-assoc
(concat flat (unnest-inner (unnest-1 nested))))))

(defn- unnest [params]
(->> (seq params)
unnest-inner
(apply concat)
(apply hash-map)))

(defn- nest-params
[request param-key]
(if-let [params (request param-key)]
(assoc request param-key (prewalk
#(if (and (vector? %) (map? (second %)))
(let [[fk m] %]
(reduce
(fn [m [sk v]]
(assoc m (str (name fk)
\[ (name sk) \]) v))
{}
m))
%)
params))
(assoc request param-key (unnest params))
request))

(defn- nest-params-request
Expand Down
8 changes: 8 additions & 0 deletions test/clj_http/test/client_test.clj
Original file line number Diff line number Diff line change
Expand Up @@ -1272,6 +1272,14 @@
{:query-params {"a" {"b" {"c" "d"}}}
:form-params {"a[b][c]" "d"}
:flatten-nested-keys [:form-params]})
(is-applied (comp client/wrap-form-params
client/wrap-nested-params)
{:query-params {"a" [{"c" "d"} "e"]}
:form-params {"a" [{"c" "d"} "e"]}
:flatten-nested-keys [:form-params]}
{:query-params {"a" [{"c" "d"} "e"]}
:form-params {"a[0][c]" "d" "a[1]" "e"}
:flatten-nested-keys [:form-params]})
(is-applied (comp client/wrap-form-params
client/wrap-nested-params)
{:query-params {"a" {"b" {"c" "d"}}}
Expand Down