-
Notifications
You must be signed in to change notification settings - Fork 0
/
client.clj
76 lines (63 loc) · 1.96 KB
/
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
(ns fifql.client
(:require
[org.httpkit.client :as http]
[clojure.tools.reader.edn :as edn]
[fif.client]))
(def ^:dynamic *fif-clojure-value-escape* '%=)
(defmacro form
"quoted form with escaped evaluation. Values preceding
*fif-clojure-value-escape* are evaluated in clojure(script).
Examples:
;; Assuming we want to pull a clojure value into a quoted form
(def x 10)
(form value %= x) ;; => '[form value 10]
Notes:
- *fif-clojure-value-escape can be replaced with a different escape
symbol as desired."
[& body]
(:result
(reduce
(fn [{:keys [result eval-next?]} atom]
(cond
(= atom *fif-clojure-value-escape*)
{:result result
:eval-next? true}
eval-next?
{:result (conj result atom)}
:else
{:result (conj result `(quote ~atom))}))
{:result []}
body)))
(defmacro sform
"Equivlant to `form`, but presents the result as a string that can
be consumed by a fifql stack-machine.
# Notes
- This should be used with the `query` function to construct the stack form.
"
[& body]
`(let [sform# (pr-str (form ~@body))]
;; Remove surrounding vector
(subs sform# 1 (dec (count sform#)))))
(defn slurp-maybe [s]
(if (string? s)
s
(slurp s)))
(defn query
"Performs a POST request on the given `url` with the given fif
`form`. Returns a map consisting of the `:stack`, `:input-string`, a
vector of strings sent to `stderr` and a vector of strings sent to
`stdout`.
# Examples
(def x 10)
(query {:url \"http://localhost:8080/fifql\"
:sform (sform %= x 2 +)})
;; {:input-string \"10 2 +\", :stack (12), :stdout [], :stderr []}
"
[url sform]
(let [options
{:body sform
:headers {"Content-Type" "application/fif"
"Accept" "application/edn"}}
result @(http/post url options)]
(when-let [sresult (-> result :body slurp-maybe)]
(edn/read-string sresult))))