All files / copacetic/lib/health-strategies/generic connect-then-ping.js

100% Statements 12/12
100% Branches 4/4
100% Functions 3/3
100% Lines 12/12

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 481x 1x   1x                   40x   40x                 29x 6x     23x   23x         23x             4x       1x  
const precond = require('precond')
const humanInterval = require('human-interval')
 
const HealthStrategy = require('../strategy')
 
/**
 * Connect to an adapter, then ping that adapter when connected
 * to check its health
 * @class
 * @extends HealthStrategy
 */
class ConnectThenPingStrategy extends HealthStrategy {
  constructor (adapter, { timeout } = {}) {
    super(timeout)
 
    this.adapter = adapter
  }
 
  /**
   * @param {String} url The connection url
   * @param {String} timeout How long to wait until giving up on a connection attempt
   * @return {Promise}
   */
  check (url, timeout = this.timeout) {
    if (this.adapter.isConnected) {
      return this.adapter.ping()
    }
 
    const connectTimeoutMS = humanInterval(timeout)
 
    precond.checkIsNumber(
      connectTimeoutMS,
      'An invalid format was used for Ping Interval, check human-interval for examples'
    )
 
    return this.adapter.connect(url, connectTimeoutMS)
  }
 
  /**
   * Destroys the connection
   */
  cleanup () {
    return this.adapter.close()
  }
}
 
module.exports = ConnectThenPingStrategy