Code coverage report for yaml-config-loader/index.js

Statements: 99.33% (148 / 149)      Branches: 80.56% (29 / 36)      Functions: 100% (34 / 34)      Lines: 100% (142 / 142)      Ignored: 4 statements, 4 branches     

All files » yaml-config-loader/ » index.js
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 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 3041 1 1 1 1 1   1 12 12 12 12 12 12 12           1 3   2 2   1 1       1 2 2                 1 7 7             1 1 1           1 2 2     1 3 3     1 2 2 2           1 10 10 10 10 10 17   10             1 2 2 2 2 1 1       1 1                 1 12 12 12 11   11 11       1               1 2 2   2 2 4   2   2 2 2 4   2         1 5           1 2 2   2 1 1 1 2   1   1 1 2 2 2           1                                 1 1 1 1 4     4 4 4 3     1 1   1                               1 5 5 5 19 19     159     83   19 19     9 9   5 5   5 5   19     5           1 9 9 9 9 24 24   9           1 11 11     1               1 21 21 42 42     21     1  
var path = require('path');
var fs = require('fs');
var util = require('util');
var yaml = require('js-yaml');
var async = require('async');
var util = require('util');
 
var Loader = function() {
  this.load = this.load.bind(this);
  this.parseYaml = this.parseYaml.bind(this);
  this.add = this.add.bind(this);
  this.context = {};
  this.loads = [];
  this.loads = [];
  this.loads = [];
};
 
/**
 * Flexible loader function that can load files from objects or directories.
 */
Loader.prototype.add = function(item, options) {
  switch (typeof item) {
    case 'string':
      this.addFileOrDirectory(item);
      break;
    case 'object':
      this.addObject(item);
      break;
  }
};
 
Loader.prototype.addFileOrDirectory = function(path) {
  this.loads.push(this.loadFileOrDirectory.bind(this, path));
  return this;
};
 
/**
 * Register a single yaml configuration path to be merged into the configuration.
 *
 * @param filePath
 *    The path on disk to register.
 */
Loader.prototype.addFile = function(filePath) {
  this.loads.push(this.loadFile.bind(this, filePath));
  return this;
};
 
/**
 * Register a directory that will have config files loaded where files loaded
 * earlier will be overridden by those loaded later.
 */
Loader.prototype.addDirectory = function(directoryPath) {
  this.loads.push(this.loadDirectory.bind(this, directoryPath));
  return this;
};
 
/**
 * Register a directory that will have config files loaded into an array.
 */
Loader.prototype.addDirectoryArray = function(directoryPath, configKey) {
  this.loads.push(this.loadDirectoryArray.bind(this, directoryPath, configKey));
  return this;
};
 
Loader.prototype.addObject = function(object, translator) {
  this.loads.push(this.loadObject.bind(this, object, this.context));
  return this;
};
 
Loader.prototype.addAndNormalizeObject = function(object, format) {
  format = format || 'camelCase';
  this.loads.push(this.loadObject.bind(this, this.translateKeyFormat(object, format), this.context));
  return this;
};
 
/**
 * Construct a configuration object from the registered paths.
 */
Loader.prototype.load = function(done) {
  var self = this;
  self.context.config = {};
  async.series(this.loads, function(error, configs) {
    var config = {};
    for (i in configs) {
      config = self.mergeConifguration(config, configs[i]);
    }
    done(error, config);
  });
};
 
/**
 * Load either a file or a directory based on path.
 */
Loader.prototype.loadFileOrDirectory = function(path, done) {
  var self = this;
  fs.stat(path, function(error, stat) {
    Iif (error) return done(error);
    if (stat.isDirectory()) {
      self.loadDirectory(path, function(error, config) {
        done(error, config);
      });
    }
    else {
      self.loadFile(path, function(error, config) {
        done(error, config);
      });
    }
  });
};
 
/**
 * Load configuration for an individual file.
 */
Loader.prototype.loadFile = function(path, done) {
  var self = this;
  fs.exists(path, function(exists) {
    if (exists) {
      fs.readFile(path, 'utf8', function(error, data) {
        /* istanbul ignore if: This error condition is near impossible to test. */
        Iif (error) return done(error);
        self.parseYaml(data, done);
      });
    }
    else {
      done(new Error(util.format('Specified configuration file `%s` not found.', path)));
    }
  });
};
 
/**
 * Load config files from a directory allowing new entries to override old.
 */
Loader.prototype.loadDirectory = function(dirPath, done) {
  var self = this;
  fs.readdir(dirPath, function(error, files) {
    /* istanbul ignore if: This error condition is near impossible to test. */
    Iif (error) return done(error);
    var loadFile = function(filePath, cb) {
      self.loadFile(path.join(dirPath, filePath), cb);
    };
    async.map(files, loadFile, function(error, confs) {
      /* istanbul ignore if: This error condition is near impossible to test. */
      Iif (error) return done(error);
      var conf = {};
      for (i in confs) {
        conf = self.mergeConifguration(conf, confs[i]);
      }
      done(null, conf);
    });
  });
};
 
Loader.prototype.loadObject = function(object, context, done) {
  return done(null, object);
};
 
/**
 * Load config files from a directory into an array.
 */
Loader.prototype.loadDirectoryArray = function(dirPath, configKey, done) {
  var self = this;
  fs.readdir(dirPath, function(error, files) {
    /* istanbul ignore if: This error condition is near impossible to test. */
    if (error) return done(error);
    var output = {};
    output[configKey] = [];
    var fileLoadHandler = function(file, cb){
      fs.readFile(path.join(dirPath, file), 'utf8', cb);
    };
    async.map(files, fileLoadHandler, function(error, confs) {
      /* istanbul ignore if: This error condition is near impossible to test. */
      Iif (error) return done(error);
      for (i in confs) {
        try {
          var conf = yaml.safeLoad(confs[i]);
          output[configKey].push(conf);
        }
        catch(e) {
          // Do something?
        }
      }
      done(null, output);
    });
  });
};
 
/**
 * Translate configuration from an object then perform a transformation on its
 * keys.
 *
 * This method is useful for loading environment variables in the form of
 * `SOME_NAME` and using them to override camel case variables like `someName`.
 *
 * @param object
 *   The object whose keys should be transformed.
 * @param keys
 *   An array of keys to load from the object.
 */
Loader.prototype.translateKeys = function(object, keys, done) {
  var output = {};
  keys = keys || Object.keys(object);
  for (i in keys) {
    var key = keys[i];
    // Covert camel case into environment variables (into all upper with
    // underscores).
    var replacer = function(match) { return '_' + match};
    var translatedName = key.replace(/[A-Z]/g, replacer).toUpperCase();
    if (object.hasOwnProperty(translatedName)) {
      output[key] = object[translatedName];
    }
  }
  Eif (done) {
    setImmediate(done.bind(null, null, output));
  }
  return output;
};
 
/**
 * Format the keys on an object converting to them to a supported format.
 *
 * @param object
 *   A plain old javascript object.
 * @param format
 *   A supported format to convert the keys to.
 *
 *   These are also the supported from formats.
 *      'camelCase' - standard camelCase with capitalization splitting parts.
 *      'CAPITAL_UNDERSCORES' - standard ENV variable format
 *      'lower-dashes' - all lower case with dashes, typical of cli parameters.
 */
Loader.prototype.translateKeyFormat = function(object, format) {
  var output = {};
  format = format || 'camelCase';
  for (key in object) {
    Eif (object.hasOwnProperty(key)) {
      var parts = key
        .split(/([A-Z][a-z]+)|_|-/g)
        .filter(function(element) {
          return element;
        })
        .map(function(item) {
          return item.toLowerCase();
        });
      var newKey = '';
      switch (format) {
        default:
        case 'camelCase':
          newKey = this.formatCamelCase(parts);
          break;
        case 'CAPITAL_UNDERSCORES':
          newKey = parts.join('_').toUpperCase();
          break;
        case 'lower-dashes':
          newKey = parts.join('-').toLowerCase();
          break;
      }
      output[newKey] = object[key];
    }
  }
  return output;
};
 
/**
 * Utility function to format an array of word parts in camelCase.
 */
Loader.prototype.formatCamelCase = function(parts) {
  var parts = parts.slice();
  var output = parts.shift();
  var part = '';
  for (i in parts) {
    part = parts[i];
    output += part.substr(0, 1).toUpperCase() + part.substring(1);
  }
  return output;
}
 
/**
 * Parse a yaml file and report an error if necessary.
 */
Loader.prototype.parseYaml = function(data, done) {
  try {
    return done(null, yaml.safeLoad(data));
  }
  catch (error) {
    setImmediate(done.bind(null, error));
  }
}
 
/**
 * Merge two confiugration objects overriding values on the first with values on
 * the second.
 */
Loader.prototype.mergeConifguration = function(one, two) {
  var i = null;
  for (i in two) {
    Eif (two.hasOwnProperty(i)) {
      one[i] = two[i];
    }
  }
  return one;
};
 
module.exports = Loader;