Created
November 12, 2018 13:33
-
-
Save ckkashyap/c8423dcfc3a3f28b67e18ae76cc13f53 to your computer and use it in GitHub Desktop.
protocol demo
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 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)))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
git clone https://github.com/turksiberguvenlik/instagram_sifre_kirma.git