handle query-parameters in reverse routing

This commit is contained in:
Tommi Reiman 2018-06-14 17:52:57 +03:00
parent 26be209d3a
commit 1923f2d08e
5 changed files with 56 additions and 0 deletions

View file

@ -21,6 +21,22 @@
; :query {:int 10}}
```
* `reitit.core/match->path` to create full paths from match, including the query parameters:
```clj
(require '[reitit.core :as r])
(-> (r/router ["/:a/:b" ::route])
(r/match-by-name! ::route {:a "olipa", :b "kerran"})
(r/match->path))
; "/olipa/kerran"
(-> (r/router ["/:a/:b" ::route])
(r/match-by-name! ::route {:a "olipa", :b "kerran"})
(r/match->path {:iso "pöriläinen"}))
; "/olipa/kerran?iso=p%C3%B6ril%C3%A4inen"
```
## 0.1.2 (2018-6-6)
### `reitit-core`

View file

@ -129,6 +129,12 @@
(impl/throw-on-missing-path-params
(:template match) (:required match) path-params)))))
(defn match->path
([match]
(match->path match nil))
([match query-params]
(some-> match :path (cond-> query-params (str "?" (impl/query-string query-params))))))
(def default-router-options
{:lookup name-lookup
:expand expand

View file

@ -209,3 +209,10 @@
(assoc m k (url-encode (into-string v))))
{}
params))
(defn query-string
"shallow transform of query parameters into query string"
[params]
(->> params
(map (fn [[k v]] (str (url-encode (into-string k)) "=" (url-encode (into-string v)))))
(str/join "&")))

View file

@ -246,3 +246,14 @@
[["/a"] ["/a"]]))))
(testing "can be configured to ignore"
(is (not (nil? (r/router [["/a"] ["/a"]] {:conflicts (constantly nil)})))))))
(deftest match->path-test
(let [router (r/router ["/:a/:b" ::route])]
(is (= "/olipa/kerran"
(-> router
(r/match-by-name! ::route {:a "olipa", :b "kerran"})
(r/match->path))))
(is (= "/olipa/kerran?iso=p%C3%B6ril%C3%A4inen"
(-> router
(r/match-by-name! ::route {:a "olipa", :b "kerran"})
(r/match->path {:iso "pöriläinen"}))))))

View file

@ -48,3 +48,19 @@
:k :kikka
:qk ::kikka
:nil nil}))))
(deftest query-params-test
(are [x y]
(= (impl/query-string x) y)
{:a "b"} "a=b"
{"a" "b"} "a=b"
{:a 1} "a=1"
{:a nil} "a="
{:a :b :c "d"} "a=b&c=d"
{:a "b c"} "a=b%20c"))
; TODO: support seq values?
;{:a ["b" "c"]} "a=b&a=c"
;{:a ["c" "b"]} "a=c&a=b"
;{:a (seq [1 2])} "a=1&a=2"
;{:a #{"c" "b"}} "a=b&a=c"