-
Notifications
You must be signed in to change notification settings - Fork 4
/
httpkit_client.clj
52 lines (42 loc) · 1.75 KB
/
httpkit_client.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
(ns clj-github.httpkit-client
(:require [cheshire.core :as cheshire]
[clj-github.token :as token]
[clj-github.utils :refer [assoc-some]]
[org.httpkit.client :as httpkit]))
(def ^:private success-codes #{200 201 202 204})
(def github-url "https://api.github.com")
(defn get-installation-token [{:keys [token-fn]}]
(token-fn))
(defn- prepare
[{:keys [token-fn]} {:keys [path method body] :or {method :get} :as request}]
(-> request
(assoc :method method)
(assoc-some :body (and body (cheshire/generate-string body)))
(assoc :url (str github-url path))
(assoc-in [:headers "Content-Type"] "application/json")
(assoc-in [:headers "Authorization"] (str "Bearer " (token-fn)))))
(defn- parse-body [content-type body]
(if (and content-type (re-find #"application/json" content-type))
(cheshire/parse-string body true)
body))
(defn- content-type [response]
(or (get-in response [:headers :content-type])
(get-in response [:headers "Content-Type"])))
(defn request [client req-map]
(let [response @(httpkit/request (prepare client req-map))]
(if (success-codes (:status response))
(update response :body (partial parse-body (content-type response)))
(throw (ex-info "Request to GitHub failed"
{:response (select-keys response [:status :body])}
(:error response))))))
(defn new-client [{:keys [app-id private-key token org] :as opts}]
(cond
token
{:token-fn (constantly token)}
app-id
{:token-fn (token/github-app-token-manager
(assoc-some {:github-app-id app-id
:github-private-key private-key}
:github-org org))}
:else
opts))