-
Notifications
You must be signed in to change notification settings - Fork 2
/
wracer.cljs
65 lines (50 loc) · 1.66 KB
/
wracer.cljs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
(ns wracer
(:require [wracer.render :refer [searching render winner show-timeout]]
[wracer.tools :refer [info]]
[clojure.browser.repl]
[goog.net.XhrIo :as xhr]
[cljs.core.async :as async :refer [chan timeout <!]])
(:require-macros
[cljs.core.async.macros :refer [go alt!]]))
(def timeout-ms 1000)
(defn now [] (.now js/Date))
(defn took [start] (- (now) start))
(defn request [method url]
(let [ch (chan)]
(xhr/send url
(fn [event]
(let [res (-> event .-target .getResponseText)]
(go (>! ch res)))) ;; close! ?
method)
ch))
(defn GET [url]
(request "GET" url))
(defn race [q]
(searching [:.yahoo :.google :.bing])
(let [t (timeout timeout-ms)
start (now)]
(go
(alt!
(GET (str "/yahoo?q=" q)) ([v] (winner :.yahoo v (took start)))
(GET (str "/bing?q=" q)) ([v] (winner :.bing v (took start)))
(GET (str "/google?q=" q)) ([v] (winner :.google v (took start)))
t ([v] (show-timeout timeout-ms))))))
;; (not in use) playground:
#_(defn search-all [q]
(searching [:.yahoo :.google :.bing])
(go
(render :.google (<! (GET (str "/google?q=" q))))
(render :.yahoo (<! (GET (str "/yahoo?q=" q))))
(render :.bing (<! (GET (str "/bing?q=" q))))))
#_(defn cors-request
"CORS in action.."
[method url]
(let [xhr (js/XMLHttpRequest.)
ch (chan)]
(.open xhr method url true)
(when xhr
(set! (.-onload xhr) (fn []
(go (>! ch (.-responseText xhr)))))
(set! (.-withCredentials xhr) true)
(.send xhr))
ch))