/
coercion.cljc
178 lines (154 loc) · 6.11 KB
/
coercion.cljc
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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
(ns reitit.coercion
(:require [clojure.walk :as walk]
[reitit.impl :as impl])
#?(:clj
(:import (java.io Writer))))
;;
;; Protocol
;;
(defprotocol Coercion
"Pluggable coercion protocol"
(-get-name [this] "Keyword name for the coercion")
(-get-options [this] "Coercion options")
(-get-apidocs [this specification data] "Returns api documentation")
(-compile-model [this model name] "Compiles a model")
(-open-model [this model] "Returns a new model which allows extra keys in maps")
(-encode-error [this error] "Converts error in to a serializable format")
(-request-coercer [this type model] "Returns a `value format => value` request coercion function")
(-response-coercer [this model] "Returns a `value format => value` response coercion function"))
#?(:clj
(defmethod print-method ::coercion [coercion ^Writer w]
(.write w (str "#Coercion{:name " (-get-name coercion) "}"))))
(defrecord CoercionError [])
(defn error? [x]
(instance? CoercionError x))
;;
;; coercer
;;
(defrecord ParameterCoercion [in style keywordize? open?])
(def ^:no-doc default-parameter-coercion
{:query (->ParameterCoercion :query-params :string true true)
:body (->ParameterCoercion :body-params :body false false)
:form (->ParameterCoercion :form-params :string true true)
:header (->ParameterCoercion :headers :string true true)
:path (->ParameterCoercion :path-params :string true true)})
(defn ^:no-doc request-coercion-failed! [result coercion value in request]
(throw
(ex-info
(str "Request coercion failed: " (pr-str result))
(merge
(into {} result)
{:type ::request-coercion
:coercion coercion
:value value
:in [:request in]
:request request}))))
(defn ^:no-doc response-coercion-failed! [result coercion value request response]
(throw
(ex-info
(str "Response coercion failed: " (pr-str result))
(merge
(into {} result)
{:type ::response-coercion
:coercion coercion
:value value
:in [:response :body]
:request request
:response response}))))
(defn extract-request-format-default [request]
(-> request :muuntaja/request :format))
;; TODO: support faster key walking, walk/keywordize-keys is quite slow...
(defn request-coercer [coercion type model {::keys [extract-request-format parameter-coercion]
:or {extract-request-format extract-request-format-default
parameter-coercion default-parameter-coercion}}]
(if coercion
(if-let [{:keys [keywordize? open? in style]} (parameter-coercion type)]
(let [transform (comp (if keywordize? walk/keywordize-keys identity) in)
model (if open? (-open-model coercion model) model)]
(if-let [coercer (-request-coercer coercion style model)]
(fn [request]
(let [value (transform request)
format (extract-request-format request)
result (coercer value format)]
(if (error? result)
(request-coercion-failed! result coercion value in request)
result))))))))
(defn extract-response-format-default [request _]
(-> request :muuntaja/response :format))
(defn response-coercer [coercion body {:keys [extract-response-format]
:or {extract-response-format extract-response-format-default}}]
(if coercion
(if-let [coercer (-response-coercer coercion body)]
(fn [request response]
(let [format (extract-response-format request response)
value (:body response)
result (coercer value format)]
(if (error? result)
(response-coercion-failed! result coercion value request response)
result))))))
(defn encode-error [data]
(-> data
(dissoc :request :response)
(update :coercion -get-name)
(->> (-encode-error (:coercion data)))))
(defn coerce-request [coercers request]
(reduce-kv
(fn [acc k coercer]
(impl/fast-assoc acc k (coercer request)))
{} coercers))
(defn coerce-response [coercers request response]
(if response
(if-let [coercer (or (coercers (:status response)) (coercers :default))]
(impl/fast-assoc response :body (coercer request response))
response)))
(defn request-coercers [coercion parameters opts]
(some->> (for [[k v] parameters
:when v]
[k (request-coercer coercion k v opts)])
(filter second)
(seq)
(into {})))
(defn response-coercers [coercion responses opts]
(some->> (for [[status {:keys [body]}] responses :when body]
[status (response-coercer coercion body opts)])
(filter second)
(seq)
(into {})))
;;
;; api-docs
;;
(defn get-apidocs [coercion specification data]
(let [swagger-parameter {:query :query
:body :body
:form :formData
:header :header
:path :path
:multipart :formData}]
(case specification
:swagger (->> (update
data
:parameters
(fn [parameters]
(->> parameters
(map (fn [[k v]] [(swagger-parameter k) v]))
(filter first)
(into {}))))
(-get-apidocs coercion specification)))))
;;
;; integration
;;
(defn compile-request-coercers
"A router :compile implementation which reads the `:parameters`
and `:coercion` data to create compiled coercers into Match under
`:result. A pre-requisite to use [[coerce!]]."
[[_ {:keys [parameters coercion]}] opts]
(if (and parameters coercion)
(request-coercers coercion parameters opts)))
(defn coerce!
"Returns a map of coerced input parameters using pre-compiled
coercers under `:result` (provided by [[compile-request-coercers]].
Throws `ex-info` if parameters can't be coerced
If coercion or parameters are not defined, return `nil`"
[match]
(if-let [coercers (:result match)]
(coerce-request coercers match)))