all files / collab/ CollabClient.js

0% Statements 0/25
0% Branches 0/8
0% Functions 0/7
0% Lines 0/25
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 65 66 67 68 69 70 71 72 73 74 75 76 77                                                                                                                                                         
import { EventEmitter } from '../util'
 
/**
  Client for CollabServer API
 
  Communicates via websocket for real-time operations
*/
class CollabClient extends EventEmitter {
  constructor(config) {
    super()
 
    this.config = config
    this.connection = config.connection
 
    // Hard-coded for now
    this.scope = 'substance/collab'
 
    // Bind handlers
    this._onMessage = this._onMessage.bind(this)
    this._onConnectionOpen = this._onConnectionOpen.bind(this)
    this._onConnectionClose = this._onConnectionClose.bind(this)
 
    // Connect handlers
    this.connection.on('open', this._onConnectionOpen)
    this.connection.on('close', this._onConnectionClose)
    this.connection.on('message', this._onMessage)
  }
 
  _onConnectionClose() {
    this.emit('disconnected')
  }
 
  _onConnectionOpen() {
    this.emit('connected')
  }
 
  /*
    Delegate incoming messages from the connection
  */
  _onMessage(msg) {
    if (msg.scope === this.scope) {
      this.emit('message', msg);
    } else if (msg.scope !== '_internal') {
      console.info('Message ignored. Not sent in hub scope', msg);
    }
  }
 
  /*
    Send message via websocket channel
  */
  send(msg) {
    if (!this.connection.isOpen()) {
      console.warn('Message could not be sent. Connection not open.', msg)
      return
    }
 
    msg.scope = this.scope;
    if (this.config.enhanceMessage) {
      msg = this.config.enhanceMessage(msg)
    }
    this.connection.send(msg)
  }
 
  /*
    Returns true if websocket connection is open
  */
  isConnected() {
    return this.connection.isOpen()
  }
 
  dispose() {
    this.connection.off(this)
  }
}
 
export default CollabClient