-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
79 lines (67 loc) · 2.13 KB
/
core.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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
(ns dev.russell.batboy.client.core
(:require [clj-http.client :as http-client]
[clojure.string :as string])
(:refer-clojure :exclude [get]))
(def ^{:private true :dynamic true} *stats-api-base-url* "https://statsapi.mlb.com/api")
; Enable debug
(def ^{:private true :dynamic true} *debug* false)
(defn- make-stats-api-url
[path]
(str *stats-api-base-url* path))
(defn- make-request-context
[options]
(merge {:as :json
:async? true}
options
(when *debug*
{:debug *debug*
:debug-body *debug*})))
(defn- async?
[context]
(:async? context))
(defn- async-call
[path context]
(let [call-promise (promise)
delivery-fn (partial deliver call-promise)]
(http-client/get (make-stats-api-url path) context delivery-fn delivery-fn)
call-promise))
(defn- sync-call
[path context]
(http-client/get (make-stats-api-url path) context))
(defn- resolve-endpoint-path-params
[endpoint context]
(let [path-params (:path-params endpoint)]
(reduce-kv
(fn [params param-key param-value]
(if-let [value (if-let [from-context (-> context :path-params param-key)]
from-context
(:default param-value))]
(assoc params param-key value)
params))
{}
path-params)))
(defn- format-path
[path params]
(let [fmt-string (string/replace path #"\{.*?\}" "%s")
var-order (mapv #(string/replace % #"\{(.*?)\}" "$1") (re-seq #"\{.*?\}" path))
replace-vars (mapv #(clojure.core/get params (keyword %)) var-order)]
(if (seq var-order)
(apply format fmt-string replace-vars)
fmt-string)))
(defn- make-path
[endpoint context]
(format-path (:path endpoint) (resolve-endpoint-path-params endpoint context)))
(defn- get-with-endpoint
[endpoint context]
(let [call-fn (if (async? context) async-call sync-call)
url (make-path endpoint context)]
(call-fn url context)))
(defn get
([endpoint]
(get endpoint {}))
([endpoint context]
(get-with-endpoint
(if (string? endpoint)
{:path endpoint}
endpoint)
(make-request-context context))))