Skip to content
Snippets Groups Projects
config.js 1.56 KiB
Newer Older
clemo's avatar
clemo committed
import fs from 'fs';
import debug from 'debug';
import path from 'path';
import env2obj from 'env2obj';
clemo's avatar
clemo committed
import _ from 'lodash';
clemo's avatar
clemo committed
const log = debug('helper:config:info');
const error = debug('helper:config:error');
clemo's avatar
clemo committed
const debg = debug('helper:config:debug');
clemo's avatar
clemo committed

clemo's avatar
clemo committed
export class Config {
clemo's avatar
clemo committed
  /**
   * Create a config.
   * @param {String} basedir path of config file - default = PWD
   * @param {prefix} prefix - of env config variables
   * e.g. APP_TITLE="hi" will be config.title
   */
clemo's avatar
clemo committed
  constructor(basedir = process.env.PWD, prefix = 'APP') {
clemo's avatar
clemo committed
    let env = process.env.NODE_ENV || 'development';
clemo's avatar
clemo committed
    process.env.NODE_ENV = env;
clemo's avatar
clemo committed
    /**
    *@object
    *the file config.js
    */
clemo's avatar
clemo committed
    this.file = {};
    if (fs.existsSync(path.join(basedir, 'config.js'))) {
      this.file = require(path.join(basedir, 'config.js'), 'utf-8')[env];
    } else {
clemo's avatar
clemo committed
      debg('file', 'did not use ', path.join(basedir, 'config.js'))
clemo's avatar
clemo committed
    }
clemo's avatar
clemo committed
    /**
    the config.default.js config
    @object
    */
clemo's avatar
clemo committed
    this.fileDefault = {};
    if (fs.existsSync(path.join(basedir, 'config.default.js'))) {
      this.fileDefault =
          require(path.join(basedir, 'config.default.js'), 'utf-8')[env]
    } else {
clemo's avatar
clemo committed
      debg('file', 'did not use ', path.join(basedir, 'config.default.js'))
clemo's avatar
clemo committed
    }
clemo's avatar
clemo committed
    /**
    *@object
    *the config.env config
    */
clemo's avatar
clemo committed
    this.env = env2obj(prefix);
clemo's avatar
clemo committed
    this.config = _.merge(this.fileDefault, this.file, this.env);
clemo's avatar
clemo committed
    // todo: lowwercase every key
clemo's avatar
clemo committed
    debg('used config', this.config)
clemo's avatar
clemo committed
  }
}
clemo's avatar
clemo committed
/**
default config loaded with PWD,APP
*/
clemo's avatar
clemo committed
const config = new Config();

exports.default = config.config;