all files / lib/strategy/ LoadAPIKeyConfigStrategy.js

91.89% Statements 34/37
85.19% Branches 23/27
100% Functions 4/4
91.89% Lines 34/37
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                12× 12×     12× 12×     12×       10× 10×                                                                
'use strict';
 
var fs = require('fs');
var extend = require('../helpers/clone-extend').extend;
var propsParser = require('properties-parser');
var expandHomeDir = require('../helpers/expand-home-dir');
 
/**
 * Represents a strategy that loads API keys from a .properties file into the configuration.
 *
 * @class
 */
function LoadAPIKeyConfigStrategy (filePath, mustExist) {
  this.filePath = filePath;
  this.mustExist = mustExist || false;
}
 
LoadAPIKeyConfigStrategy.prototype.process = function (config, callback) {
  var mustExist = this.mustExist;
  var filePath = expandHomeDir(this.filePath);
 
  // In case we don't have a home path but specified a '~' in our path...
  if (filePath === false) {
    if (mustExist) {
      return callback(new Error("Unable to load '" + this.filePath + "'. Environment home not set."));
    }
    return callback(null, config);
  }
 
  fs.exists(filePath, function (exist) {
    if (!exist) {
      if (mustExist) {
        callback(new Error('Client API key file not found: ' + filePath));
      } else {
        callback(null, config);
      }
    } else {
      // Extend config with default client apiKey fields.
      extend(config, {
        client: {
          apiKey: {}
        }
      });
 
      Iif (!mustExist && config.client.apiKey.id && config.client.apiKey.secret) {
        return callback(null, config);
      }
 
      propsParser.read(filePath, function (err, result) {
        Iif (err) {
          return callback(err);
        }
 
        Iif (!result) {
          result = {};
        }
 
        // If we don't require the file to exist and if the key
        // file is empty, then just ignore it.
        if (!mustExist && Object.keys(result).length === 0) {
          return callback(null, config);
        }
 
        var apiKeyId = result['apiKey.id'];
        var apiKeySecret = result['apiKey.secret'];
 
        if (!apiKeyId || !apiKeySecret) {
          return callback(new Error('Unable to read properties file: ' + filePath));
        }
 
        config.client.apiKey.id = apiKeyId;
        config.client.apiKey.secret = apiKeySecret;
 
        callback(null, config);
      });
    }
  });
};
 
module.exports = LoadAPIKeyConfigStrategy;