-
Notifications
You must be signed in to change notification settings - Fork 0
/
core.clj
96 lines (76 loc) · 2.64 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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
(ns async-tasks-client.core
(:use [medley.core :only [remove-vals]])
(:require [cemerick.url :as curl]
[cheshire.core :as json]
[clj-http.client :as http]
[clojure.string :as string]
[clojure.tools.logging :as log]))
(defprotocol Client
"A client library for the async-tasks API."
(get-by-id
[_ id]
"Fetches an async task by ID")
(delete-by-id
[_ id]
"Deletes an async task by ID")
(add-status
[_ id status]
"Adds a status to an existing task by ID, passing in a map which specifies the new status to add.")
(add-behavior
[_ id behavior]
"Adds a behavior to an existing task by ID, passing in a map which specifies the new behavior to add.")
(get-by-filter
[_ filters]
"Get a set of async tasks that match the provided filters.")
(create-task
[_ task]
"Create a new task and mint an ID for it."))
(defn- async-tasks-url
[base-url & components]
(log/debug "using async-tasks base URL" base-url)
(str (apply curl/url base-url (map curl/url-encode components))))
(defn- get-options
[params & {:keys [as] :or {as :stream}}]
{:query-params params
:as as
:follow-redirects false})
(defn- post-options
[body params & {:keys [as] :or {as :stream}}]
{:query-params params
:body body
:content-type :json
:as as
:follow-redirects false})
(def ^:private delete-options get-options)
(def ^:private put-options post-options)
(defn- normalize-id [id-or-uri]
(string/replace id-or-uri #".*/tasks/" ""))
(deftype AsyncTasksClient [base-url]
Client
(get-by-id
[_ id]
(:body (http/get (async-tasks-url base-url "tasks" (normalize-id id)) (get-options {} :as :json))))
(delete-by-id
[_ id]
(:body (http/delete (async-tasks-url base-url "tasks" (normalize-id id)) (get-options {} :as :json))))
(create-task
[_ task]
(->> (http/post (async-tasks-url base-url "tasks") (post-options (json/encode task) {} :as :json))
:headers
:location))
(add-status
[_ id status]
(->> (http/post (async-tasks-url base-url "tasks" (normalize-id id) "status") (post-options (json/encode status) {} :as :json))
:headers
:location))
(add-behavior
[_ id behavior]
(->> (http/post (async-tasks-url base-url "tasks" (normalize-id id) "behaviors") (post-options (json/encode behavior) {} :as :json))
:headers
:location))
(get-by-filter
[_ filters]
(:body (http/get (async-tasks-url base-url "tasks") (get-options filters :as :json)))
))
(defn new-async-tasks-client [base-url]
(AsyncTasksClient. base-url))