1
0
Fork 0
mirror of https://github.com/rails/rails.git synced 2022-11-09 12:12:34 -05:00
rails--rails/actioncable/lib/assets/javascripts/action_cable/connection.coffee

85 lines
1.8 KiB
CoffeeScript
Raw Normal View History

2015-07-08 08:42:04 -04:00
# Encapsulate the cable connection held by the consumer. This is an internal class not intended for direct user manipulation.
{message_types} = ActionCable.INTERNAL
class ActionCable.Connection
2015-10-14 18:09:10 -04:00
@reopenDelay: 500
2015-06-25 16:24:58 -04:00
constructor: (@consumer) ->
@open()
send: (data) ->
if @isOpen()
2015-07-06 21:43:50 -04:00
@webSocket.send(JSON.stringify(data))
true
else
false
open: =>
if @webSocket and not @isState("closed")
throw new Error("Existing connection must be closed before opening")
else
@webSocket = new WebSocket(@consumer.url)
@installEventHandlers()
true
close: ->
2015-07-06 21:43:50 -04:00
@webSocket?.close()
reopen: ->
2015-10-14 18:09:10 -04:00
if @isState("closed")
@open()
else
try
@close()
finally
setTimeout(@open, @constructor.reopenDelay)
isOpen: ->
@isState("open")
2015-07-07 08:57:57 -04:00
# Private
isState: (states...) ->
@getState() in states
getState: ->
2015-07-06 21:43:50 -04:00
return state.toLowerCase() for state, value of WebSocket when value is @webSocket?.readyState
null
2015-07-07 08:57:57 -04:00
installEventHandlers: ->
for eventName of @events
handler = @events[eventName].bind(this)
@webSocket["on#{eventName}"] = handler
2015-10-14 18:09:32 -04:00
return
2015-07-07 08:57:57 -04:00
events:
message: (event) ->
{identifier, message, type} = JSON.parse(event.data)
switch type
when message_types.confirmation
@consumer.subscriptions.notify(identifier, "connected")
when message_types.rejection
@consumer.subscriptions.reject(identifier)
else
@consumer.subscriptions.notify(identifier, "received", message)
2015-07-07 08:57:57 -04:00
open: ->
@disconnected = false
@consumer.subscriptions.reload()
2015-07-07 08:57:57 -04:00
close: ->
@disconnect()
2015-07-07 08:57:57 -04:00
error: ->
@disconnect()
disconnect: ->
return if @disconnected
@disconnected = true
@consumer.subscriptions.notifyAll("disconnected")
2015-07-07 09:43:22 -04:00
toJSON: ->
state: @getState()