-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathlink.clj
60 lines (53 loc) · 2.14 KB
/
link.clj
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
(ns net.thegeez.w3a.link
(:require [clojure.string :as string]
[io.pedestal.interceptor :as interceptor]
[io.pedestal.http.route :as route]
[io.pedestal.log :as log]))
(defn link [context kw-name & options]
(let [linker (get-in context [:bindings #'route/*url-for*])
{:keys [absolute? query-params]
:or {absolute? true}} options
[scheme port] (if (get-in context [:request :headers "x-forwarded-proto"])
[:https 443]
[:http nil])]
(apply linker kw-name
:absolute? absolute?
:scheme scheme
:port port
;; TODO also auto insert ?format= param based on current request
:query-params query-params
options)))
(defn self [context]
(when-let [kw-name (get-in context [:route :route-name])]
(link context kw-name :query-params (get-in context [:request :query-params]))))
(defn next-or-link [context link-name & opts]
(let [next (get-in context [:request :query-params :next])]
(if (and next
(seq next))
next
(apply link context link-name opts))))
(defn link-with-next [context link-name & opts]
(apply link context link-name (mapcat identity
(if-let [next (get-in context [:request :params :next])]
(assoc-in opts [:params :next] next)
opts))))
(defmulti coerce-param (fn [type v]
type))
(defmethod coerce-param :long
[_ v]
(try
(Long/parseLong v)
(catch Exception _ nil)))
(defn coerce-path-params [name+type]
(interceptor/interceptor
{:name ::coerce-path-params
:enter (fn [context]
(update-in context [:request :path-params]
(fn [params]
(reduce-kv
(fn [m k v]
(if-let [type (get name+type k)]
(assoc m k (coerce-param type v))
(assoc m k v)))
{}
params))))}))