firehoseio / js_client

Javascript Firehose client
MIT License
0 stars 2 forks source link

Consider building a singleton for connection management #16

Open steel opened 7 years ago

steel commented 7 years ago
adam-h commented 6 years ago

@steel How do you propose the API would work?

Currently we have (currently - pseudo ish code):

let myConsumer = new FirehoseConnection(channel, options)
myConsumer.on("data", doStuff) //similar for old callback style
myConsumer.on("failed", showError) //similar for old callback style
// ... later
myConsumer.disconnect()

How are you thinking of managing:

steel commented 6 years ago

We should disable the option of even not using multi-plexed connections. WebSocket connections are always multi-plexed.

I imagining this simple reference tracker and garbage collecting system


class Channel
  constructor: (name, @wsConnection) ->
    # event handlers string: [handler functions]
    @handlers = {}
    @name = name

     # connect to channel
     @wsConnection.send "subscribe", name
     @wsConnection.on "message", @handleMessage

  remove: ->
    @wsConnection.send "unsubscribe from channel"

  on: (event, handler) ->
    @handlers[event].push handler
    @trigger "addListener"

  off: (event, handler) ->
    # remove from table
    @handlers[event][handler] = null
    @trigger "removeListener"

  handleMessage: (channel, msg) ->
    if channel == @name
      # iterate through handlers and call them with the message
      @handlers["message"].forEach (fn) -> fn(msg)

class Firehose
  constructor: ->
    # channels is a map of string to Channel objects
    @channels = {}

  bind: (channel) ->
    # look up if channel is exists or not
    channel = new Channel(name)
    channel.on "removeListener", @pruneChannels

    # if channel doesn't exist, create one and connect it
    # then put it in the lookup table

  pruneChannels: ->
    # iterate through channels and remove channels that have no listeners

# In a view

# get access to this channel
channel = Firehose.subscribe "my/channel"
channel.on "message", handleMessage

# when removing the view
channel.off "message", handleMessage