-
Notifications
You must be signed in to change notification settings - Fork 0
/
axios_client.cljs
88 lines (77 loc) · 2.4 KB
/
axios_client.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
78
79
80
81
82
83
84
85
86
87
88
(ns com.avisi-apps.gaps.brevo.axios-client
(:refer-clojure :exclude [get])
(:require
["axios" :as axios]
["agentkeepalive" :refer [HttpsAgent]]
[cljs-bean.core :refer [->clj ->js bean]]
[goog.uri.utils :as gutils]
[promesa.core :as p]
[clojure.string :as string]))
(defn stringify-query-params [m]
(gutils/buildQueryDataFromMap (->js m)))
(def https-agent
(HttpsAgent.
(clj->js
{:keepAlive true
:maxSockets 100
:maxFreeSockets 10
:timeout 30000
:freeSocketTimeout 30000})))
(def axios-instance
(axios/create
(clj->js
{;; cap the maximum content length we'll accept to 1MBs, just in case
:maxContentLength (* 1 1000 1000)
:maxRedirects 0
:httpsAgent https-agent})))
(defn endpoint-with-qp [{:keys [endpoint query-params]}]
(let [query-string (stringify-query-params query-params)]
(cond-> endpoint (not (string/blank? query-string)) (str "?" query-string))))
(defn request [{:keys [method endpoint headers data query-params]}]
(let [url (endpoint-with-qp
{:endpoint endpoint
:query-params query-params})]
(->
(.request
^js axios-instance
(cond->
{:url url
:method (name method)
:headers (merge {:content-type "application/json"} headers)}
data (assoc :data data)
:always ->js))
(p/then ->clj)
(p/catch
(fn [err]
(let [{:keys [response]} (bean err)
{:keys [status]
:as res}
(some->
response
bean)]
(throw
(ex-info
"Failed HTTP request"
{:url url
:method method
:request-data data
:response-data (js->clj (:data res))
:status status}))))))))
(defn get [env] (request (assoc env :method :get)))
(defn put [env] (request (assoc env :method :put)))
(defn post [env] (request (assoc env :method :post)))
(defn delete [env] (request (assoc env :method :delete)))
(defn axios-error? [err] (:isAxiosError err false))
(defn axios-error->json [{:keys [response request]}]
(cond
response
(->
(bean response)
(select-keys [:status :data :headers])
(assoc :type-of-failure :axios-response-failure))
request
(->
(bean request)
(select-keys [:config])
(assoc :type-of-failure :axios-request-failure))
:else {:type-of-failure :axios-unexpected-error}))