/
stub.clj
106 lines (69 loc) · 1.9 KB
/
stub.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
97
98
99
100
101
102
103
104
105
106
(ns farseer.stub
(:require
[farseer.jetty :as jetty]
[farseer.spec.stub :as spec.stub]
[farseer.error :as e]
[clojure.tools.logging :as log]
[clojure.spec.alpha :as s]))
(def ex? (partial instance? Throwable))
(defn make-rpc-handlers [stub-handlers]
(reduce-kv
(fn [rpc-handlers method result]
(assoc-in rpc-handlers
[method :handler/function]
(cond
(fn? result)
result
(ex? result)
(fn [& _]
(throw result))
:else
(fn [& _]
result))))
{}
stub-handlers))
(defn update-handlers
[config]
(let [{stub-handlers :stub/handlers} config
rpc-handlers (make-rpc-handlers stub-handlers)]
(assoc config :rpc/handlers rpc-handlers)))
(defmacro with-stub
[config & body]
`(let [config# ~config]
(s/assert ::spec.stub/config config#)
(let [config# (update-handlers config#)
server# (jetty/start-server config#)]
(try
~@body
(finally
(jetty/stop-server server#))))))
(defn with-stubs-impl
[[& configs] & body]
(loop [form `(do ~@body)
configs (reverse configs)]
(let [[config & configs] configs]
(if config
(recur `(with-stub ~config ~form)
configs)
form))))
(defmacro with-stubs
[[& configs] & body]
(apply with-stubs-impl configs body))
;;
;; Handlers that trigger RPC exceptions.
;;
(defn ->err-handler [data-error]
(fn [context params]
(e/error! data-error)))
(def parse-error
(->err-handler e/parse-error))
(def invalid-request
(->err-handler e/invalid-request))
(def not-found
(->err-handler e/not-found))
(def invalid-params
(->err-handler e/invalid-params))
(def internal-error
(->err-handler e/internal-error))
(def auth-error
(->err-handler e/auth-error))