Skip to content

Instantly share code, notes, and snippets.

@ckkashyap
Created November 12, 2018 13:33
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ckkashyap/c8423dcfc3a3f28b67e18ae76cc13f53 to your computer and use it in GitHub Desktop.
Save ckkashyap/c8423dcfc3a3f28b67e18ae76cc13f53 to your computer and use it in GitHub Desktop.
protocol demo
(ns protocol
(:require-macros [cljs.core.async.macros :refer [go go-loop]])
(:require
[goog.net.XhrIo :as xhr]
[goog.json :as gjson]
[cljs.core.async :as async :refer [chan close! <! >!]]))
(defn do-request [endpoint method headers body]
(let [ch (chan)]
(xhr/send endpoint
(fn [event]
(let [target (-> event .-target)
res (.getResponseText target)
code (.getStatus target)
parsed (js->clj (gjson/parse res))
response (if (= code 200)
{:type :ok
:message parsed}
{:type :error
:message parsed})]
(go (>! ch response))))
method
body
(goog.structs.Map. (clj->js headers)))
ch))
(defn get-token [endpoint secret]
(let [input-chan (do-request endpoint "POST" "" {"Authorization" (str "Bearer: " secret)})
output-chan (chan)
_ (go (let [input-result (<! input-chan)
token (if (= :ok (:type input-result)) ((:message input-result) "token") :error)
result token]
(>! output-chan result)))]
output-chan))
(defn get-message [endpoint token]
(let [input-chan (do-request endpoint "GET" "" {"Authorization" (str "Bearer: " token)})
output-chan (chan)
_ (go (let [input-result (<! input-chan)]
(>! output-chan input-result)))]
output-chan))
(defn do-poll [endpoint token ch]
(let [in-ch (get-message endpoint token)
f (fn []
(go
(let [m (<! in-ch)
_ (>! ch m)
_ (js/setTimeout (fn [] (do-poll endpoint token ch)) 1000)])))]
(f)))
(defn get-stream [token-endpoint message-endpoint secret]
(let [stream (chan)
token-channel (get-token token-endpoint secret)
_ (go (let [token (<! token-channel)
_ (do-poll message-endpoint token stream)]))]
stream))
(def s (get-stream "http://localhost:3000/get-token/user1" "http://localhost:3000/get-message" "123"))
(go
(loop []
(let [m (<! s)]
(println m)
(recur))))
@omerensar49
Copy link

@omerensar49
Copy link

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment