All files / lib/classes/kubiks Config.js

98.38% Statements 61/62
96.96% Branches 32/33
100% Functions 8/8
100% Lines 54/54

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 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 1445x   5x 5x                         11x 11x 7x       4x   11x 11x                     14x 13x   13x 2x 2x   11x 10x 9x                 11x 11x 11x 19x 19x 19x 15x 1x   15x 14x     4x 3x   1x     10x 10x 10x                 10x 10x 10x 10x 863x 863x 2x 2x 2x   2x   10x                 1x 1x               2x               3x 2x 1x   2x                   3x       5x   5x  
const { Kubik, helpers } = require('../../Rubik');
 
const set = require('lodash/set');
const get = require('lodash/get');
 
/**
 * Layered cake, ie config
 * Need to configure the application with layers
 * @namespace Rubik
 * @class Config
 * @param {Array<String>|String} defaultVolume initial volumes
 * @prop {Array<String>} volumes volumes for search configs
 * @prop {Object} configs        cached configs
 */
class Config extends Kubik {
  constructor(defaultVolume) {
    super();
    if (defaultVolume) {
      this.volumes = Array.isArray(defaultVolume)
        ? defaultVolume.concat([])
        : [defaultVolume];
    } else {
      this.volumes = [];
    }
    this.name = 'config';
    this.configs = {};
  }
 
  /**
   * Get config
   * @param  {String}  name         name of field what we want to get
   * @param  {Boolean} [cache=true] flag; get config from cache or scan volumes again?
   * @return {Mixed}                config or empty object, if nothing found
   */
  get(name, cache = true) {
    // If name is empty return empty config
    if (!name) return {};
    const split = name.split('.');
    // If name has dot notation
    if (split.length > 1) {
      if (!cache) this.scan(split[0]);
      return get(this.configs, name);
    }
    if (cache && this.configs[name]) return this.configs[name];
    this.scan(name);
    return this.configs[name];
  }
 
  /**
   * Scan volumes to search config field
   * @param  {String} name field name
   * @return {Config}      this
   */
  scan(name) {
    const len = this.volumes.length;
    const currentOptions = {};
    for (var i = 0; i < len; i++) {
      const volume = this.volumes[i];
      try {
        let options = require(`${volume}${name}`);
        if (typeof options === 'function') {
          options = options(this);
        }
        if (typeof options === 'object') {
          helpers.assignDeep(currentOptions, options);
        }
      } catch (err) {
        if (/Cannot find module .*?/.test(err.message)) {
          continue;
        }
        throw err;
      }
    }
    this.configs[name] = currentOptions;
    this.scanEnv(name);
    return this;
  }
 
  /**
   * Scan environment for field with name
   * @param  {[type]} name [description]
   * @return {[type]}      [description]
   */
  scanEnv(name) {
    const env = process.env;
    const keys = Object.keys(env);
    const currentOptions = {};
    for (const key of keys) {
      const pattern = new RegExp(`^${name}($|_[^_].*?$)`);
      if (!pattern.test(key)) continue;
      let options = env[key];
      try {
        options = JSON.parse(options);
      } catch(err) { /* skip err */ }
      set(currentOptions, key.replace(/_/g, '.'), options);
    }
    helpers.assignDeep(this.configs, currentOptions);
  }
 
  /**
   * Remove cached field
   * @param  {String} name field name
   * @return {Config}      this
   */
  removeCache(name) {
    this.configs[name] = undefined;
    return this;
  }
 
  /**
   * Clear all cached fields
   * @return {Config} this
   */
  clearCache() {
    this.configs = {};
  }
 
  /**
   * Use extension
   * @param  {Object} extension extension object
   */
  use(extension) {
    if (!extension) return;
    if (Array.isArray(extension.volumes)) {
      this.volumes = this.volumes.concat(extension.volumes);
    }
    if (extension.clearCache) this.clearCache();
  }
 
  /**
   * up config
   * @return {Config} this
   */
  up() {
    // add config to quick get from app
    // if some one create another config, and change it name, this will be omitted
    Iif (this.name === 'config' && !this.app.config) this.app.config = this;
  }
}
 
Config.prototype.reset = Config.prototype.removeCache;
 
module.exports = Config;