🔧 Use automatic validation in token proxies

This commit is contained in:
Andrés Moya
2025-12-09 11:09:38 +01:00
parent e8ff89836e
commit b786b8e07a
4 changed files with 33 additions and 13 deletions

View File

@@ -95,12 +95,12 @@
(defn assoc-key
"Add a key & value to a schema"
[s k v]
(mu/assoc s k v))
(mu/assoc (schema s) k v))
(defn dissoc-key
"Remove a key from a schema"
[s k]
(mu/dissoc s k))
(mu/dissoc (schema s) k))
(defn ref?
[s]

View File

@@ -114,7 +114,8 @@
(defn token-set-proxy
[plugin-id file-id id]
(obj/reify {:name "TokenSetProxy"}
(obj/reify {:name "TokenSetProxy"
:wrap u/wrap-errors}
:$plugin {:enumerable false :get (constantly plugin-id)}
:$file-id {:enumerable false :get (constantly file-id)}
:$id {:enumerable false :get (constantly id)}
@@ -206,16 +207,14 @@
(token-proxy plugin-id file-id id token-id)))))
:addToken
(fn [attrs]
(let [schema (-> (sm/schema (cfo/make-token-schema
{:schema [:tuple (-> (cfo/make-token-schema
(-> (u/locate-tokens-lib file-id)
(ctob/get-tokens id))))
(sm/dissoc-key :id)) ;; We don't allow plugins to set the id
attrs (u/coerce attrs schema :addToken "invalid token attrs")]
(when attrs
(ctob/get-tokens id)))
(sm/dissoc-key :id))] ;; We don't allow plugins to set the id
:fn (fn [attrs]
(let [token (ctob/make-token attrs)]
(st/emit! (dwtl/create-token id token))
(token-proxy plugin-id file-id (:id set) (:id token))))))
(token-proxy plugin-id file-id (:id set) (:id token))))}
:duplicate
(fn []

View File

@@ -254,3 +254,19 @@
[values]
(let [s (set values)]
(if (= (count s) 1) (first s) "mixed")))
(defn wrap-errors
"Function wrapper to be used in plugin proxies methods to handle errors.
When an exception is thrown, a readable error message is output to the console
and the exception is captured."
[f]
(fn []
(let [args (js-arguments)]
(try
(.apply f nil args)
(catch :default cause
(display-not-valid (ex-message cause) (obj/stringify args))
(if-let [explain (-> cause ex-data ::sm/explain)]
(println (sm/humanize-explain explain))
(js/console.log (ex-data cause)))
nil)))))

View File

@@ -106,6 +106,11 @@
(identical? (.getPrototypeOf js/Object o)
(.-prototype js/Object)))))
#?(:cljs
(defn stringify
[obj]
(js/JSON.stringify obj)))
;; EXPERIMENTAL: unsafe, does not checks and not validates the input,
;; should be improved over time, for now it works for define a class
;; extending js/Error that is more than enought for a first, quick and