All files index.js

96.77% Statements 30/31
86.21% Branches 25/29
100% Functions 4/4
100% Lines 29/29
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 651x 1x 1x 1x     1x 2x 2x       1x     14x 1x     14x     14x 63x 2x     2x 2x 2x       14x 1x       13x 4x 2x 2x               13x 2x         2x 10x 10x         13x    
const extend = require('extend');  // deep clone, not like shallow Object.assign
const config = require('./defaults');
const errors = require('./errors');
require('dotenv').config({ silent: true });
 
// Check if a variable is numeric even if string
const is = {
  numeric: num => !isNaN(num),
  boolean: b => b === true || b === false
    || (typeof b === 'string' && ['true', 'false'].includes(b.toLowerCase()))
};
 
module.exports = (user = {}, plugins, app) => {
 
  // If it's a number it's the port
  if (typeof user === 'number') {
    user = { port: user };
  }
 
  let options = extend(true, {}, config, user);
 
  // Overwrite with the env variables if set
  for (let key in options) {
    if (key.toUpperCase().replace(/\s/g, '_') in process.env) {
      let env = process.env[key.toUpperCase().replace(/\s/g, '_')];
 
      // Convert it to Number if it's numeric
      if (is.numeric(env)) env = +env;
      Iif (is.boolean(env)) env = typeof env === 'string' ? env === 'true' : env;
      options[key] = env;
    }
  }
 
  if (options.secret === 'your-random-string-here') {
    throw errors.NotSoSecret();
  }
 
  // Load the options from the plugin array, namespaced with the plugin name
  if (plugins) {
    plugins.forEach(plugin => {
      let opts = plugin.options;
      options[plugin.name] = extend(true,
        opts instanceof Function ? opts(options) : opts,
        options[plugin.name] || {}
      );
    });
  }
 
 
  if (app) {
    app.options = options;
 
    // Set them into express' app
    // TODO: whitelist here of name:type from
    //   https://expressjs.com/en/api.html#app.settings.table
    for (let key in options) {
      Eif (app.set && ['boolean', 'number', 'string'].includes(typeof options[key])) {
        app.set(key, options[key]);
      }
    }
  }
 
  return options;
}