DEV Community

Discussion on: Adventures of a Hobbyist ~ Part Three

Collapse
 
link2twenty profile image
Andrew Bone • Edited

I think I found a solution that works for me, I like the idea of the file being .conf and I found this Node Module. It had a few bits I didn't like so I wrote a wrapper around it. Here's what I've ended up with.

class ConfHelper {
  constructor() {
    const Conf = require('conf');
    const EM = require('events');
    this.events = new EM.EventEmitter();
    this.config = new Conf({
      configName: 'ignis',
      fileExtension: 'conf',
      cwd: '.'
    });
    this._getConf();
  }
  _getConf(key, type) {
    this.conf = this.config.get();
    this.events.emit('change', key, type);
  }
  createKey(key, val) {
    if (this.config.has(key)) throw `${key} already exists, please use updateConf`
    let keyVal = this.conf;
    let layers = key.split('.');
    let name = layers[layers.length - 1];
    for (let i = 0; i < layers.length - 1; i++) {
      if (!keyVal[layers[i]]) keyVal[layers[i]] = {};
      keyVal = keyVal[layers[i]];
    }
    keyVal[name] = val;
    this.config.set(layers[0], this.conf[layers[0]]);
    this._getConf(key, "create");
  }
  deleteKey(key) {
    if (!this.config.has(key)) return
    this.config.delete(key);
    this._getConf(key, "delete");
  }
  updateKey(key, val) {
    if (!this.config.has(key)) throw `${key} does not exists please use createConf`
    if (this.config.get(key) === val) return
    this.config.set(key, val);
    this._getConf(key, "update");
  }
}

module.exports = ConfHelper;

And here is the test I wrote to go with it.

const ConfHelper = require('./conf_import');
const ch = new ConfHelper()

ch.events.on('change', (key, type) => {
  let event =`
  -------
  type    ${type}               
  key     ${key}                
  newVal  ${ch.config.get(key)} 
  -------`;
  console.log(event)
});

ch.createKey('General.version', "v0.0.1");
ch.updateKey('General.version', "v0.0.2");
ch.deleteKey('General.version');

Which outputs

  -------
  type    create
  key     General.version
  newVal  v0.0.1
  -------

  -------
  type    update
  key     General.version
  newVal  v0.0.2
  -------

  -------
  type    delete
  key     General.version
  newVal  undefined
  -------

Thanks for all your help 🙂