All files / copacetic/lib/health-strategies/http strategy.js

100% Statements 13/13
100% Branches 4/4
100% Functions 5/5
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                 49x   49x                   26x   26x         26x       25x 9x     16x             49x  
const precond = require('precond')
const humanInterval = require('human-interval')
 
const HealthStrategy = require('../strategy')
 
/**
 * Checks the availability of a service running over http
 * @class
 * @extends HealthStrategy
 */
class HttpStrategy extends HealthStrategy {
  constructor (httpAdapter, { timeout } = {}) {
    super(timeout)
 
    this.httpAdapter = httpAdapter
  }
 
  /**
   * @param {String} url The endpoint used to check a service's health
   * @param {String} [timeout] The service becomes unhealthy if it does not
   * response within this period
   * @return {Promise}
   */
  check (url, timeout = this.timeout) {
    const timeoutMS = humanInterval(timeout)
 
    precond.checkIsNumber(
      timeoutMS,
      'An invalid format was used for Ping Interval, check human-interval for examples'
    )
 
    return this
      .httpAdapter
      .request(url, { timeout: timeoutMS })
      .then((res) => {
        if (this.httpAdapter.clientErr(res)) {
          return Promise.reject(res)
        }
 
        return Promise.resolve(res)
      })
  }
 
  cleanup () {}
}
 
module.exports = (adapter, opts) => new HttpStrategy(adapter, opts)