|
| 1 | +(ns pogonos.context |
| 2 | + (:require [clojure.string :as str] |
| 3 | + [pogonos.protocols :as proto])) |
| 4 | + |
| 5 | +(defn- lookup* [stack keys] |
| 6 | + (if-let [k (peek keys)] |
| 7 | + (when-let [v (loop [stack stack] |
| 8 | + (when-let [v (peek stack)] |
| 9 | + (if (and (map? v) |
| 10 | + (not #?(:clj (identical? (v k ::none) ::none) |
| 11 | + :cljs (keyword-identical? (v k ::none) ::none)))) |
| 12 | + v |
| 13 | + (recur (next stack)))))] |
| 14 | + (if (next keys) |
| 15 | + (get-in v keys) |
| 16 | + (v k))) |
| 17 | + (peek stack))) |
| 18 | + |
| 19 | +(defrecord NonCheckingContext [stack] |
| 20 | + proto/IContext |
| 21 | + (lookup [_ keys] |
| 22 | + (lookup* stack keys)) |
| 23 | + (push [_ val] |
| 24 | + (NonCheckingContext. (conj stack val)))) |
| 25 | + |
| 26 | +(defrecord CheckingContext [stack on-missing-key] |
| 27 | + proto/IContext |
| 28 | + (lookup [_ keys] |
| 29 | + (or (lookup* stack keys) |
| 30 | + (on-missing-key stack keys))) |
| 31 | + (push [_ val] |
| 32 | + (CheckingContext. (conj stack val) on-missing-key))) |
| 33 | + |
| 34 | +(defmulti ^:private ->on-missing-key-fn (fn [x] x)) |
| 35 | + |
| 36 | +(defmethod ->on-missing-key-fn :default [x] |
| 37 | + (if (fn? x) |
| 38 | + x |
| 39 | + (throw |
| 40 | + (ex-info (str ":on-missing-key must be :error or a function, but got " (type x)) {})))) |
| 41 | + |
| 42 | +(defmethod ->on-missing-key-fn :error [_] |
| 43 | + (fn [stack keys] |
| 44 | + (let [k (->> keys (map name) (str/join \.))] |
| 45 | + (throw (ex-info (str "Key \"" k "\" not found in the given context") |
| 46 | + {:key k :context (last stack)}))))) |
| 47 | + |
| 48 | +(defn make-context |
| 49 | + ([data] (make-context data {})) |
| 50 | + ([data {:keys [on-missing-key]}] |
| 51 | + (let [stack (list data)] |
| 52 | + (if on-missing-key |
| 53 | + (->CheckingContext stack (->on-missing-key-fn on-missing-key)) |
| 54 | + (->NonCheckingContext stack))))) |
0 commit comments