Skip to content

Commit ea26572

Browse files
committed
Make validate-tx handle nested schemas
1 parent c073bb7 commit ea26572

File tree

1 file changed

+46
-14
lines changed

1 file changed

+46
-14
lines changed

src/com/biffweb/impl/xtdb2.clj

Lines changed: 46 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -176,32 +176,64 @@
176176
(UUID/fromString (str (subs (str uuid-prefix) 0 4)
177177
(subs (str uuid-rest) 4))))
178178

179+
180+
(comment
181+
;; maybe use code like this if we want to validate :update operations
182+
183+
optional-keys (into #{}
184+
(comp (filter (comp :optional :properties val))
185+
(map key))
186+
(:keys (malli/ast schema*)))
187+
188+
(into {}
189+
(remove (fn [[k v]]
190+
(and (nil? v)
191+
(optional-keys k))))
192+
record)
193+
)
194+
195+
(defn- optional-keys-ast [ast malli-opts]
196+
(-> ast
197+
(malli/from-ast malli-opts)
198+
malli.u/optional-keys
199+
malli/ast))
200+
201+
(defn- optional-keys
202+
"Similar to malli.util/optional-keys but recursive, in case schema is e.g. something like
203+
[:and ... [:map ...]]"
204+
[schema malli-opts]
205+
(let [ast (-> schema
206+
malli/deref-recursive
207+
malli/ast)]
208+
(malli/from-ast
209+
((fn step [ast]
210+
(cond
211+
(= (:type ast) :map)
212+
(optional-keys-ast ast malli-opts)
213+
214+
(not-empty (:children ast))
215+
(update ast :children #(mapv step %))
216+
217+
:else
218+
ast))
219+
ast)
220+
malli-opts)))
221+
179222
(defn validate-tx [tx malli-opts]
180223
(doseq [tx-op tx
181224
:when (#{:put-docs :patch-docs} (first tx-op))
182225
:let [[op opts & records] tx-op
183226
table (if (keyword? opts)
184227
opts
185228
(:into opts))
186-
schema* (malli/schema table malli-opts)
187-
schema (cond-> schema*
188-
(= op :patch-docs) malli.u/optional-keys)
189-
optional-keys (into #{}
190-
(comp (filter (comp :optional :properties val))
191-
(map key))
192-
(:keys (malli/ast schema*)))]
229+
schema (cond-> (malli/schema table malli-opts)
230+
(= op :patch-docs) (optional-keys malli-opts))]
193231
record records]
194232
(when-not (some? (:xt/id record))
195233
(throw (ex-info "Record is missing an :xt/id value."
196234
{:table table
197235
:record record})))
198-
(when-not (malli/validate schema
199-
(into {}
200-
(remove (fn [[k v]]
201-
(and (nil? v)
202-
(optional-keys k))))
203-
record)
204-
malli-opts)
236+
(when-not (malli/validate schema record malli-opts)
205237
(throw (ex-info "Record doesn't match schema."
206238
{:table table
207239
:record record

0 commit comments

Comments
 (0)