-
-
Notifications
You must be signed in to change notification settings - Fork 93
/
util.cljs
77 lines (66 loc) · 2.12 KB
/
util.cljs
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
(ns cljs-http.util
(:refer-clojure :exclude [uri?])
(:import goog.Uri)
(:require [clojure.string :refer [blank? capitalize join split lower-case]]
[cognitect.transit :as t]
[goog.userAgent :as agent]
[no.en.core :refer [base64-encode]]))
(defn basic-auth
"Returns the value of the HTTP basic authentication header for
`credentials`."
[credentials]
(when credentials
(let [[username password]
(if (map? credentials)
(map credentials [:username :password])
credentials)]
(str "Basic " (base64-encode (str username ":" password))))))
(defn build-url
"Build the url from the request map."
[{:keys [scheme server-name server-port uri query-string]}]
(str (doto (Uri.)
(.setScheme (name (or scheme :http)))
(.setDomain server-name)
(.setPort server-port)
(.setPath uri)
(.setQuery query-string true))))
(defn camelize
"Returns dash separated string `s` in camel case."
[s]
(->> (split (str s) #"-")
(map capitalize)
(join "-")))
(defn build-headers
"Build the headers from the map."
[m] (clj->js (zipmap (map camelize (keys m)) (vals m))))
(defn user-agent
"Returns the user agent."
[] (agent/getUserAgentString))
(defn android?
"Returns true if the user agent is an Android client."
[] (re-matches #"(?i).*android.*" (user-agent)))
(defn transit-decode
"Transit decode an object from `s`."
[s type opts]
(let [rdr (t/reader type opts)]
(t/read rdr s)))
(defn transit-encode
"Transit encode `x` into a String."
[x type opts]
(let [wrtr (t/writer type opts)]
(t/write wrtr x)))
(defn json-decode
"JSON decode an object from `s`."
[s]
(let [v (if-not (clojure.string/blank? s) (js/JSON.parse s))]
(when (some? v)
(js->clj v :keywordize-keys true))))
(defn json-encode
"JSON encode `x` into a String."
[x] (js/JSON.stringify (clj->js x)))
(defn parse-headers [headers]
(reduce
#(let [[k v] (split %2 #":\s+")]
(if (or (blank? k) (blank? v))
%1 (assoc %1 (lower-case k) v)))
{} (split (or headers "") #"(\n)|(\r)|(\r\n)|(\n\r)")))