all files / app/bin/static/public/ socketApi.js

90.32% Statements 28/31
60% Branches 6/10
87.5% Functions 7/8
90.32% Lines 28/31
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                                              
;(function () {
  var mqtt = require('mqtt')
  var Backo = require('backo')
  var backoff = new Backo({ min: 100, max: 2000 })
  var isHttps = /^https:/
  var clients = {}
  var clientApi = {
    disconnect: function (urlPrefix) {
      var client = clients[ urlPrefix ]
      delete clients[ urlPrefix ]
      client.end()
      console.log('%s: disconnecting', urlPrefix)
    },
    connectWithPrefix: function (urlPrefix, sessionId, authFunction, isDebug) {
      Iif (isDebug) {
        console.log('connecting with %s', urlPrefix)
      }
      var client = clients[ urlPrefix ]
      if (!client) {
        client = clients[ urlPrefix ] = mqtt.connect(urlPrefix + '/mqtt', {
          protocol: isHttps.test(urlPrefix) ? 'wss' : 'ws',
          qos: 0
        })
        backoff.reset()
        client.on('connect', function () {
          backoff.reset()
        })
        client.on('error', function (err) {
          Eif (/Not authorized|Invalid password/.test(err.message)) {
            setTimeout(function () {
              authFunction(function (err, token) { // eslint-disable-line handle-callback-err
                client.options.username = 'Bearer'
                client.options.password = token
                client._reconnect()
              })
            }, backoff.duration())
          }
          Iif (isDebug) {
            console.error(new Date().toISOString(), err)
          }
        })
      }
      return client
    },
    connect: function (sessionId, authFunction, isDebug, callback) {
      return clientApi.connectWithPrefix(window.location.origin, sessionId, authFunction, isDebug, callback)
    }
  }
  module.exports = clientApi
})()