Skip to content

Instantly share code, notes, and snippets.

@onetom
Created May 4, 2016 08:46
Show Gist options
  • Save onetom/7c8631099dbb423b9d21cc8a461dada6 to your computer and use it in GitHub Desktop.
Save onetom/7c8631099dbb423b9d21cc8a461dada6 to your computer and use it in GitHub Desktop.
Minimal Castra client
(ns auth-core
(:require-macros
[hoplon.core :refer [with-init! defelem]]
[javelin.core :refer [defc defc= cell= dosync]]
[compile-time-config :refer [env]])
(:require
[hoplon.core :refer :all]
[hoplon.storage-atom :refer [local-storage]]
[javelin.core :refer [cell]]
[castra.core :refer [mkremote assoc-when xhr-resp-headers]]
[cognitect.transit :as t]))
(def id-token (-> (cell nil) (local-storage 'id-token)))
(def clj->json (partial t/write (t/writer :json)))
(def json->clj (partial t/read (t/reader :json)))
(defn remote [endpoint result-cell error-cell loading-cell]
(fn [& args]
(let [body (clj->json `[~endpoint ~@args])
headers {;"X-Castra-Tunnel" "transit"
"X-Castra-Csrf" "true" ; Backend looks for its existance
"Accept" "application/transit+json"
"Authorization" (when-let [jwt @id-token]
(str "Bearer " jwt))}
xhr-opts (-> {"async" true
"contentType" "application/transit+json"
"data" body
"dataType" "text"
"headers" headers
"processData" false
"type" "POST"
"url" (str (env :backend-url) "/stupid")
"timeout" 0
"xhrFields" {"withCredentials" true}})
ajax-promise (.ajax js/jQuery (clj->js xhr-opts))
decode-response (fn [data] (json->clj data))]
(doto ajax-promise
(.done (fn [data text-status jqXHR]
(let [{:keys [ok error]} (decode-response data)]
(if ok
(dosync
(reset! result-cell ok)
(reset! error-cell nil))
(reset! error-cell error)))))
(.fail (fn [jqXHR text-status error-thrown]
(reset! error {:text-status text-status
:error-thrown error-thrown})))))))
(def get-current-user
(remote
'api/get-current-user
current-user
error
loading))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment