forked from dardevelin/taiga-events-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsubscription.coffee
52 lines (36 loc) · 1.38 KB
/
subscription.coffee
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
queue = require('./rabbit')
class Subscription
constructor: (@client_id, @auth, @ws, @routing_key) ->
handleMessage: (msg) ->
content = JSON.parse(msg.content.toString())
if content.session_id == @auth.sessionId
return
clientMsg = content
clientMsg.routing_key = msg.fields.routingKey
clientMsgStr = JSON.stringify(clientMsg)
try
@ws.send clientMsgStr
catch e
console.error("Error: ", e)
start: () ->
queue.subscribe(@client_id, @routing_key, @.handleMessage.bind(@))
stop: () ->
queue.unsubscribe(@client_id, @routing_key)
class SubscriptionManager
constructor: (@client_id, @auth, @ws) ->
@.subscriptions = {}
add: (routing_key) ->
if [email protected][routing_key]
@.subscriptions[routing_key] = {}
else
@.subscriptions[routing_key].stop()
@.subscriptions[routing_key] = new Subscription(@client_id, @auth, @ws, routing_key)
@.subscriptions[routing_key].start()
remove: (routing_key) ->
if @.subscriptions[routing_key] && @.subscriptions[routing_key].stop
@.subscriptions[routing_key].stop()
delete @.subscriptions[routing_key]
destroy: () ->
@.subscriptions = {}
queue.destroy(@client_id)
exports.SubscriptionManager = SubscriptionManager