-
Notifications
You must be signed in to change notification settings - Fork 4
/
client.cljs
58 lines (45 loc) · 1.56 KB
/
client.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
(ns wscljs.client
(:require [wscljs.format :as fmt]
[wscljs.spec :as ws-spec]
[cljs.spec.alpha :as s]))
(defn status [socket]
"Retrieves the connection status of the socket."
(condp = (.-readyState socket)
0 :connecting
1 :open
2 :stopping
3 :stopped))
(defn create
"Starts a websocket connection and returns it.
Takes the following arguments:
url => the websocket url
handler-map => a hashmap containing handler functions mapping to:
- :on-open => called when opening a socket connection
- :on-message => called when recieving message on the socket
- :on-close => called when closing a socket connection
Usage:
(require '[wscljs.client :as ws]
'[wscljs.format :as fmt])
(def socket (ws/create \"ws://....\" handler-map))
(ws/send socket data fmt/json)
"
[url {:keys [on-open on-message on-close] :as handler-map}]
{:pre [(s/valid? ::ws-spec/websocket-handler-map handler-map)]}
(if-let [sock (js/WebSocket. url)]
(do
(set! (.-onopen sock) on-open)
(set! (.-onmessage sock) on-message)
(set! (.-onclose sock) on-close)
sock)
(throw (js/Error. (str "Web socket connection failed: " url)))))
(defn send
"Sends data over socket in the specified format."
([socket data]
(send socket data fmt/identity))
([socket data format]
{:pre [(s/valid? ::ws-spec/websocket-open socket)]}
(.send socket (fmt/write format data))))
(defn close
"Closes the socket connection."
[socket]
(.close socket))