Created
October 26, 2016 19:06
-
-
Save AdamFrey/f489f8d7f6a3a63b64ee29e5dc6ca8a3 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(ns biz.castra | |
(:require [castra.middleware :as c] | |
[castra.core :as r :refer [ex ex? dfl-ex *pre* *request* *session* *validate-only*]])) | |
(def head {"X-Castra-Tunnel" "transit"}) | |
;; Private castra fns | |
(def castra-req? #'c/castra-req?) | |
(def csrf! #'c/csrf!) | |
(def do-rpc #'c/do-rpc) | |
(def ex->clj #'c/ex->clj) | |
(def select-vars #'c/select-vars) | |
(defn wrap-castra-errors [handler] | |
(let [body-keys nil] ;; From original impl | |
(fn [req] | |
(if-not (castra-req? req) | |
(handler req) | |
;; Castra error | |
(try (handler req) | |
(catch Throwable e | |
(let [h (c/headers req head {"Content-Type" "application/json"}) | |
d (c/response body-keys req {:error (ex->clj e)})] | |
{:status 200, :headers h, :body d}))))))) | |
(defn wrap-castra [handler & [opts & more :as namespaces]] | |
(let [{:keys [body-keys state-fn] :as opts} (when (map? opts) opts) | |
nses (if opts more namespaces) | |
seq* #(or (try (seq %) (catch Throwable e)) [%]) | |
vars (fn [] (->> nses (map seq*) (mapcat #(apply select-vars %)) set))] | |
(fn [req] | |
(if-not (castra-req? req) | |
(handler req) | |
(binding [*print-meta* true | |
*pre* true | |
*request* req | |
*validate-only* (= "true" (get-in req [:headers "x-castra-validate-only"]))] | |
(let [h (c/headers req head {"Content-Type" "application/json"}) | |
f #(do (csrf!) (do-rpc (vars) (c/expression body-keys req))) | |
d (c/response body-keys req {:result (f) :state (when state-fn (state-fn))})] | |
{:status 200, :headers h, :body d})))))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment