All files / src/Logger BaseLogger.js

84.37% Statements 27/32
69.23% Branches 9/13
100% Functions 7/7
84.37% Lines 27/32

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 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 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119                    1x 1x       1x         1x     1x     1x       1x 1x 1x         1x 1x             17x 3x     14x               13x                     13x             13x               4x             4x             17x 17x     17x 17x       28x       10x 10x       1x      
// @ts-check
import { EventEmitter } from "events";
import { bindAll, get, hasIn, noop, now, sortedLastIndexBy, toString } from "lodash";
import { genId } from "../utils";
import Cookies from "js-cookie";
 
/**
 * @typedef {import('./BaseLogger').Error} LoggerError
 */
 
export const MAX_ERRORS_SIZE = 100;
export const LOCAL_STORAGE_FIELD = "baseLogger";
 
class Logger extends EventEmitter {
  constructor() {
    super();
    /*
    enable/disable auto-reload feature
    should be disabled in tests environements (where partial back-ends are used)
     */
    this.autoReload = true;
 
    /** @type {Array<LoggerError>} */
    this._errors = [];
 
    /** @type {string} */
    this._field = `${window.location.pathname}${LOCAL_STORAGE_FIELD}`;
 
    // Load errors from localstorage
    let errorFromLocalStorage;
    try {
      errorFromLocalStorage = JSON.parse(localStorage.getItem(this._field) || "[]");
      this._errors = errorFromLocalStorage;
    }
    catch { /** noop */ }
 
    /* error messages must be handled */
    this.on("error", noop);
    bindAll(this, [ "error", "warning" ]);
  }
 
  /**
   * @param {any} error
   */
  _wrapMessage(error) {
    if (hasIn(error, "message")) {
      return hasIn(error, "name") ?
        (error.name + ": " + error.message) : error.message;
    }
    return toString(error);
  }
 
  /**
   * @param {any} error
   */
  error(error) {
    /* axios network error */
    Iif (this.autoReload &&
        (get(error, "message") === "Network Error") &&
        !Cookies.get("auth-reload-cookie")) {
      console.log("Network error, force-reloading the page");
      Cookies.set("auth-reload-cookie", "1", { "max-age": "10" });
      // @ts-ignore (some browsers have an extra argument)
      window.location.reload(true);
      return;
    }
 
    /** @type {LoggerError} */
    const err = {
      id: genId(),
      message: this._wrapMessage(error),
      error: error,
      timestamp: now(),
      type: "error"
    };
    this._storeAndEmit(err);
  }
 
  /**
   * @param {any} warning
   */
  warning(warning) {
    /** @type {LoggerError} */
    const warn = {
      id: genId(),
      message: this._wrapMessage(warning),
      error: warning,
      timestamp: now(),
      type: "warning"
    };
    this._storeAndEmit(warn);
  }
 
  /**
   * @param {any} errOrWarn
   */
  _storeAndEmit(errOrWarn) {
    this._errors.splice(sortedLastIndexBy(this._errors, errOrWarn, "timestamp"), 0, errOrWarn);
    Iif (this._errors.length > MAX_ERRORS_SIZE) {
      this._errors.splice(0, this._errors.length - MAX_ERRORS_SIZE);
    }
    this.emit("error", errOrWarn);
    localStorage.setItem(this._field, JSON.stringify(this._errors));
  }
 
  getErrors() {
    return this._errors;
  }
 
  clear() {
    this._errors = [];
    localStorage.setItem(this._field, JSON.stringify(this._errors));
  }
}
 
const logger = new Logger();
 
export default logger;