-
Notifications
You must be signed in to change notification settings - Fork 0
/
api_3.cljs
79 lines (67 loc) · 1.67 KB
/
api_3.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
(ns dgknght.app-lib.api-3
(:refer-clojure :exclude [get])
(:require [cljs.core.async :as a]
[cljs-http.client :as http]
[dgknght.app-lib.api :as og]))
(def default-opts
{:headers {"Content-Type" "application/json"
"Accept" "application/json"}})
(def path og/path)
(defn- singular?
[v]
(and v
(not (sequential? v))))
(defn- pluralize
[x]
(if x
(if (singular? x)
[x]
x)
[]))
(defn- build-xf
[{:keys [pre-xf post-xf]}]
(apply comp
(concat (pluralize pre-xf)
[(map #(or (:body %) %))]
(pluralize post-xf))))
(defn- build-chan
[{:as opts
:keys [on-error]
:or {on-error (fn [e]
(println "An error occurred processing the channel request: " e))}}]
(a/chan 1 (build-xf opts) on-error))
(defn- wait-and-callback
[ch {:keys [callback]
:or {callback identity}}]
(a/go
(let [res (a/<! ch)]
(callback res))))
(defn- build-req
[opts]
(-> default-opts
(merge opts)
(update-in [:channel] #(or % (build-chan opts)))))
(defn get
([uri] (get uri {}))
([uri opts]
(wait-and-callback
(http/get uri (build-req opts))
opts)))
(defn post
([uri resource] (post uri resource {}))
([uri resource opts]
(wait-and-callback
(http/post uri (assoc (build-req opts) :json-params resource))
opts)))
(defn patch
([uri resource] (patch uri resource {}))
([uri resource opts]
(wait-and-callback
(http/patch uri (assoc (build-req opts) :json-params resource))
opts)))
(defn delete
([uri] (delete uri {}))
([uri opts]
(wait-and-callback
(http/delete uri (build-req opts))
opts)))