-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathschema.clj
280 lines (241 loc) · 11 KB
/
schema.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
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
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
(ns grape.schema
(:require [schema.core :as s]
[schema.spec.core :as spec]
[schema.spec.leaf :as leaf]
[grape.utils :refer :all]
[slingshot.slingshot :refer [throw+ try+]]
[grape.store :as store]
[schema-tools.core :as st]
[schema-tools.coerce :as stc]
[schema.coerce :as coerce]
[monger.util :refer [object-id]]
[clj-time.core :as t]
[clj-time.format :as f]
[clojure.tools.logging :refer [log]]
[schema-tools.core.impl :as stc-impl]
[schema.spec.variant :as variant]
[com.rpl.specter :refer [ALL]]
)
(:import (schema.utils ValidationError)
(schema.core Predicate Constrained Schema)
(org.bson.types ObjectId)
(org.joda.time DateTime)))
(def ^:dynamic *deps* {})
(def ^:dynamic *resource* {})
(def ^:dynamic *request* {})
(def ^:dynamic *payload* {})
(def ^:dynamic *existing* {})
(def ? s/optional-key)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; VALIDATORS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defn resource-exists? [resource-key]
(fn [id]
(let [resource (resource-key (:resources-registry *deps*))
deps-store (:store *deps*)
source (get-in resource [:datasource :source])]
(pos? (store/count deps-store source
{:find {:_id id}}
{:soft-delete? (:soft-delete *resource*)})))))
(defn unique? [field]
(fn [item]
(let [deps-store (:store *deps*)
source (get-in *resource* [:datasource :source])]
(zero? (store/count deps-store source
{:find (merge {field item}
(when-let [id (:_id *existing*)]
{:_id {:$ne id}}))}
{:soft-delete? (:soft-delete *resource*)})))))
(defn insensitive-unique? [field]
(fn [item]
(let [deps-store (:store *deps*)
source (get-in *resource* [:datasource :source])]
(zero? (store/count deps-store source
{:find (merge {field {:$regex (str "^" item "$") :$options "i"}}
(when-let [id (:_id *existing*)]
{:_id {:$ne id}}))}
{:soft-delete? (:soft-delete *resource*)})))))
(def email?
(partial re-matches #"^[^@]+@[^@\\.]+[\\.].+"))
(def url?
(partial re-matches #"^https?:\/\/(?:(?!-)[a-zA-Z0-9-]{1,63}(?<!-)\.)+[a-zA-Z]{2,63}(?:\:[0-9]{2,5})?(?:\/[a-zA-Z0-9\/%@!?$&|\'()*+,#;=.~_-]*)?$"))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;;; SCHEMA VARIANTS
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(defrecord ResourceEmbedded [resource-key field schema]
Schema
(spec [this]
(variant/variant-spec
spec/+no-precondition+
[{:schema schema}]))
(explain [this] (list 'resource-embedded resource-key)))
(defn resource-embedded [resource-key field schema]
(s/constrained (->ResourceEmbedded resource-key field schema) (resource-exists? resource-key) "resource-should-exist"))
(defrecord ResourceJoin [resource-key field schema]
Schema
(spec [this]
(leaf/leaf-spec
(spec/precondition this (constantly false) (fn [_] "this key is read-only"))))
(explain [this] (list 'resource-join resource-key field)))
(defn resource-join [resource-key field]
(->ResourceJoin resource-key field s/Any))
(defrecord ReadOnly [schema]
s/Schema
(spec [this]
(leaf/leaf-spec
(spec/precondition this (constantly false) (fn [_] "this key is read-only"))))
(explain [this] (list 'read-only (s/explain schema))))
(defn read-only [schema] (->ReadOnly schema))
(defrecord Hidden [schema]
s/Schema
(spec [this]
(leaf/leaf-spec
(spec/precondition this (constantly true) (fn [_] ""))))
(explain [this] (list 'hidden (s/explain schema))))
(defn hidden [schema] (->Hidden schema))
(def default stc-impl/default)
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Utils
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def primitive? #{s/Int s/Num s/Bool s/Str s/Any ObjectId DateTime})
(def maybe? (partial instance? schema.core.Maybe))
(def hidden? (partial instance? Hidden))
(def read-only? (partial instance? ReadOnly))
(def resource-embedded? (partial instance? ResourceEmbedded))
(def resource-join? (partial instance? ResourceJoin))
(defn walk-schema [schema key-fn value-fn
& {:keys [skip-hidden? skip-read-only? skip-unwrap-for transform-map transform-seq]
:or {skip-hidden? false skip-read-only? false skip-unwrap-for (fn [path v] false)
transform-map (fn [path v] v) transform-seq (fn [path v] v)}
:as args}]
((fn walk [path v]
(cond
(or (primitive? v) (skip-unwrap-for path v))
(value-fn path v)
(and (record? v) (seq (:schemas v)))
(walk path (first (:schemas v)))
(record? v)
(walk path (:schema v))
(map? v)
(->> v
(filter (fn [[k v]]
(when-not (or (and skip-hidden? (hidden? v))
(and skip-read-only? (or (read-only? v) (resource-join? v))))
[k v])))
(map (fn [[k v]]
(let [k (key-fn k)]
[k (walk (conj path k) v)])))
(into {})
(transform-map path))
(sequential? v)
(let [walked (walk (conj path []) (first v))]
(transform-seq path [walked]))))
[] schema))
(defn get-schema-keyseqs [schema & {:keys [skip-hidden? skip-read-only?]}]
(let [keyseqs (volatile! #{})]
(walk-schema schema s/explicit-schema-key (fn [path _]
(vswap! keyseqs conj path)
nil)
:skip-hidden? skip-hidden?
:skip-read-only? skip-read-only?
:transform-map (fn [path m]
(when (seq m)
(vswap! keyseqs conj path))
m)
:transform-seq (fn [path v]
(when (seq v)
(vswap! keyseqs conj path))
v))
(into #{} (filter seq @keyseqs))))
(defn get-schema-relations
"this function gets a schema as its input and returns a map of a Specter path to the corresponding relation spec"
[schema]
(let [relations (volatile! {})]
(walk-schema schema
s/explicit-schema-key
(fn [path value]
(assert (not (and (resource-join? value)
(seq (->> path drop-last (filter sequential?)))))
"schema error: relation spec join in an object having a parent array in not supported")
(cond
(resource-embedded? value)
(vswap! relations assoc path {:type :embedded :resource (:resource-key value)})
(resource-join? value)
(vswap! relations assoc path {:type :join :resource (:resource-key value) :field (:field value)}))
value)
:skip-unwrap-for (fn [path v]
(or (resource-embedded? v)
(resource-join? v))))
(->> @relations
(map (fn [[k v]]
[(mapv #(if (= % []) ALL (keyword %)) k) v]))
(into {}))))
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
;; Validation
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
(def object-id-matcher
{ObjectId (coerce/safe #(object-id ^String %))})
(def date-time-matcher
(let [date-formatter (get-in *deps* [:config :date-formatter] (f/formatters :date-time))]
{DateTime (coerce/safe #(f/parse date-formatter %))}))
(defn cleve-coercion-matcher [schema]
(or (stc/default-coercion-matcher schema)
(object-id-matcher schema)
(date-time-matcher schema)
(coerce/json-coercion-matcher schema)))
(defn translate-error [err] err)
(defn map-validation-error [error]
{:type :validation-failed
:error
(clojure.walk/postwalk
(fn [el]
(cond
(and (instance? ValidationError el) (= (type (.-schema el)) java.lang.Class))
(translate-error "type-invalid")
(and (instance? ValidationError el)
(= (.-fail-explanation el) 'read-only))
(translate-error "read-only")
(and (instance? ValidationError el)
(instance? Predicate (.-schema el)))
(translate-error (:pred-name (.-schema el)))
(and (instance? ValidationError el)
(instance? Constrained (.-schema el)))
(if (vector? (:post-name (.-schema el)))
(translate-error (second (:post-name (.-schema el))))
(translate-error (:post-name (.-schema el))))
(symbol? el)
(translate-error (str el))
(and (instance? ValidationError el)
(= (.-fail-explanation el) 'not))
(str (.-schema el))
(instance? ValidationError el)
(s/explain (.-schema el))
:else el))
error)})
(defn validate [payload schema]
(try+
(stc/coerce payload schema cleve-coercion-matcher)
(catch [:type :schema-tools.coerce/error] {:keys [error]}
(throw (ex-info "validation failed" (map-validation-error error))))))
(defn validate-create [{:keys [hooks] :as deps} resource request payload]
(binding [*deps* deps
*resource* resource
*request* request
*payload* payload]
(validate payload (:schema resource))))
(defn validate-update [{:keys [hooks] :as deps} resource request payload existing]
(binding [*deps* deps
*resource* resource
*request* request
*payload* payload
*existing* existing]
(validate payload (:schema resource))))
(defn validate-partial-update [{:keys [hooks] :as deps} resource request payload existing]
(binding [*deps* deps
*resource* resource
*request* request
*payload* payload
*existing* existing]
;; for partial update, the schema should have all of its keys optional
(let [schema (st/optional-keys (:schema resource))]
(validate payload schema))))