all files / src/ Config.js

100% Statements 18/18
100% Branches 8/8
100% Functions 4/4
100% Lines 18/18
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                                                                                             
"use strict";
 
const Parser = require("./Parser");
const path = require("path");
 
class Config {
 
  /**
   * Constructor
   * @param  {Object|String} passedConfigParam Object or string with desired configuration
   */
  constructor(passedConfigParam) {
    if (this._isConfigPassed(passedConfigParam)) {
      const passedConfig = this._getPassedConfig(passedConfigParam);
 
      this.config = Object.assign({}, passedConfig);
    } else {
      this.defaultConfig = require("./defaultConfig");
      this.config = Object.assign({}, this.defaultConfig);
    }
  }
 
  /**
   * Gets the config
   * @return {Object} Config object
   */
  get() {
    return this.config;
  }
 
  /**
   * Checks whether config has been passed or not
   * @param  {Object|String}  passedConfig    Object or string with desired configuration
   * @return {Boolean}                        True if config is present, false if it isn't
   */
  _isConfigPassed(passedConfig) {
    const noKeysLength = 0;
 
    return typeof passedConfig !== "undefined" && Object.keys(passedConfig).length !== noKeysLength;
  }
 
  /**
   * Loads the config
   * @param  {Object|String} passedConfig  File path if string. Config object also accepted.
   * @return {Object}                         Config JSON
   */
  _getPassedConfig(passedConfig) {
    if (typeof passedConfig === "string") {
      const parser = new Parser();
      let configFile = passedConfig;
 
      if (!path.isAbsolute(passedConfig)) {
        configFile = path.join(__dirname, passedConfig);
      }
 
      return parser.parse(configFile);
    }
 
    return passedConfig;
  }
 
}
 
module.exports = Config;