all files / lib/config/ index.js

86.02% Statements 80/93
67.65% Branches 23/34
100% Functions 14/14
71.74% Lines 33/46
7 statements, 4 functions, 5 branches Ignored     
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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179                     10×               10×                                                                                                                                           36× 27×                                     453×   453×                 453×               11×                                                      
import path from 'path';
import fs from 'fs';
import {EventEmitter} from 'events';
import findUp from 'find-up';
import isUndefined from 'lodash/isUndefined';
import getObjectValue from 'lodash/get';
import each from 'lodash/each';
import * as CONSTANTS from '../constants';
import Parse from '../parse';
 
/**
 * Object of event names assigned to an object for easy reference.
 * @type {Object.<string, string>}
 * @const
 */
export const EVENTS = {
  CONFIG_UPDATED: 'CONFIG_UPDATED'
};
 
export default class Config extends EventEmitter {
  constructor() {
    super();
 
    /**
     * Full path to where we're running our app from.
     * @type {string} Full path.
     * @private
     */
    this._root;
 
    /**
     * Raw object that holds the config object.
     * @type {Object}
     * @private
     */
    this._raw = Object.create(null);
 
    /**
     * Default values for configuration properties that must exist.
     * @type {Object}
     * @private
     */
    this._defaults = Config.defaultConfig();
  }
 
  /**
   * Look for a `_config.yml` file in this directory or any parent directories.
   * @return {string} Path to the local `_config.yml` file.
   */
  findLocal() {
    // Look up directories to find a '_config.yml' file.
    let configYmlPath = findUp.sync(CONSTANTS.YAML.CONFIG);
 
    // If we still can't find a '_config.yml' file then throw an error.
    if (!configYmlPath) {
      throw new Error(`No '${CONSTANTS.YAML.CONFIG}' file found.`);
    }
 
    return configYmlPath;
  }
 
  /**
   * Find the directory where our local '_config.yml' exists.
   * @return {string} Path to the directory where our '_config.yml' file exists.
   */
  findLocalDir() {
    return this.findLocal().replace(CONSTANTS.YAML.CONFIG, '');
  }
 
  /**
   * Set the root path of where we're executing from. If it's different than
   * our previous stored value then we re-load the local config.
   * @param {string} rootPath Absoute path.
   */
  setRoot(rootPath) {
    const oldPath = this._root;
 
    // Update new root.
    this._root = rootPath;
 
    Eif (oldPath !== this._root) {
      this.loadLocal();
    }
  }
 
  loadLocal() {
    let localConfigPath = path.join(this._root, CONSTANTS.YAML.CONFIG);
    let localConfig = '';
    try {
      localConfig = fs.readFileSync(localConfigPath, 'utf8');
    } catch (e) {
      // noop.
    }
 
    let newConfig = Parse.fromYaml(localConfig);
 
    this.update(newConfig);
  }
 
  update(config = {}) {
    // Store config data privately.
    this._raw = config;
 
    Iif (isUndefined(config.path)) {
      throw new Error('_config.yml requires a \'path\' value.');
    }
 
    // Calculate absolute path of 'paths' keys.
    this._raw.path[CONSTANTS.KEY.SOURCE] = path.resolve(
      this._root, this._raw.path[CONSTANTS.KEY.SOURCE]
    );
    each(this._raw.path, (val, key) => {
      if (key !== CONSTANTS.KEY.SOURCE) {
        this._raw.path[key] = path.resolve(
          this._raw.path.source,
          this._raw.path[key]
        );
      }
    });
 
    // Notify listeners that config has been updated.
    this.emit(EVENTS.CONFIG_UPDATED);
  }
 
  /**
   * Getter to access config properties. Everything is pushed through here
   * so we can provide required defaults if they're not set. Also enforces
   * uniform access to config properties.
   * @param {string} objectPath Path to object property, i.e. 'path.source'.
   * @return {*} Config value.
   */
  get(objectPath = '') {
    let value = getObjectValue(this._raw, objectPath);
 
    Iif (isUndefined(value)) {
      value = getObjectValue(this._defaults, objectPath);
 
      if (isUndefined(value)) {
        throw new Error(`Tried to access config '${objectPath}' ` +
          'that does not exist.');
      }
    }
 
    return value;
  }
 
  /**
   * Reads and parses the default config YAML file from package.
   * @return {Object} Parsed default config.
   */
  static defaultConfig() {
    return Parse.fromYaml(
      fs.readFileSync(path.resolve(__dirname, 'defaults.yml'), 'utf8')
    );
  }
 
  /**
   * Reads and parses the example config YAML file from package.
   * @return {Object} Parsed default config.
   */
  static exampleConfig() {
    return Parse.fromYaml(
      fs.readFileSync(path.resolve(__dirname, 'config_example.yml'), 'utf8')
    );
  }
 
  /**
   * Helper function that creates a new Config instance with the '_config.yml'
   * file already loaded.
   * @param {string} root Optional give a root path.
   * @return {Config} Config instance.
   */
  static create(root) {
    let config = new Config();
    config.setRoot(root || config.findLocalDir());
    return config;
  }
}