all files / src/Ping/ index.js

80% Statements 24/30
55.56% Branches 10/18
66.67% Functions 4/6
82.14% Lines 23/28
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                                                                                 
/**
 * Creates a Ping instance.
 * @returns {Ping}
 * @constructor
 */
let Ping = function(opt) {
  this.opt = opt || {};
  this.favicon = this.opt.favicon || "/favicon.ico";
  this.timeout = this.opt.timeout || 0;
  this.logError = this.opt.logError || false;
};
 
/**
 * Pings source and triggers a callback when completed.
 * @param source Source of the website or server, including protocol and port.
 * @param callback Callback function to trigger when completed. Returns error and ping value.
 * @param timeout Optional number of milliseconds to wait before aborting.
 */
Ping.prototype.ping = function(source, callback) {
  let self = this;
  self.wasSuccess = false;
  self.img = new Image();
  self.img.onload = onload;
  self.img.onerror = onerror;
 
  let timer;
  let start = new Date();
 
  function onload(e) {
    self.wasSuccess = true;
    pingCheck.call(self, e);
  }
 
  function onerror(e) {
    self.wasSuccess = false;
    pingCheck.call(self, e);
  }
 
  Eif (self.timeout) {
    timer = setTimeout(function() {
      pingCheck.call(self, undefined);
    }, self.timeout); }
 
  /**
   * Times ping and triggers callback.
   */
  function pingCheck() {
    Eif (timer) { clearTimeout(timer); }
    let pong = new Date() - start;
    Eif (typeof callback === "function") {
      // When operating in timeout mode, the timeout callback doesn't pass [event] as e.
      // Notice [this] instead of [self], since .call() was used with context
      Iif (!this.wasSuccess) {
        if (self.logError) { console.error("error loading resource"); }
        return callback("error", pong);
      }
      return callback(null, pong);
    }
  }
  self.img.src = source + self.favicon + "?" + (+new Date()); // Trigger image load with cache buster
};
 
module.exports = Ping;