import * as Fs from 'fs-extra'; import * as _ from 'lodash'; import * as Cache from 'memory-cache'; import * as extendify from 'extendify'; export class Config { constructor() { if (_.isNull(Cache.get('config'))) { Cache.put('config', this.raw()); } } raw() { try { return require(Cache.get('configfile')); } catch (err) { throw err; } } get(key, defaultResponse) { let getObject; try { getObject = _.reduce(_.split(key, '.'), (o, i) => o[i], Cache.get('config')); } catch (err2) { _.noop(); } if (!_.isUndefined(getObject)) { return getObject; } return (!_.isUndefined(defaultResponse)) ? defaultResponse : undefined; } save(json, next) { if (!json || !_.isObject(json) || _.isNull(json) || !_.keys(json).length) { throw new Error('Invalid JSON was passed to Builder.'); } Fs.writeJson(Cache.get('configfile'), json, { spaces: 2 }, (err) => { if (!err) Cache.put('config', json); return next(err); }); } modify(object, next) { if (!_.isObject(object)) return next(new Error('Function expects an object to be passed.')); const deepExtend = extendify({ inPlace: false, arrays: 'replace', }); const modifiedJson = deepExtend(Cache.get('config'), object); Fs.writeJson(Cache.get('configfile'), { spaces: 2 }, (err) => { if (err) return next(err); Cache.put('config', modifiedJson); return next(); }); } }