UNPKG

hoppa-cli

Version:
76 lines (68 loc) 1.85 kB
var fs = require('fs'), os = require('os'), path = require('path'); class Store { constructor(name) { var dir = path.join(os.homedir(), '.task'); fs.existsSync(dir) || fs.mkdirSync(dir); this.file = path.join(dir, name); this.changed = false; try { var contents = fs.readFileSync(this.file, { encoding: 'utf8' }); this.data = JSON.parse(contents); } catch (e) { // ignore } this.data = this.data || {}; } /** * Prefill values if doesn't exists */ init(data) { Object.keys(data).forEach(key => { this.data[key] = this.data[key] || data[key]; }); } /** * Save changes to file system */ commit(force = false) { if (!this.changed && !force) return; fs.writeFileSync(this.file, JSON.stringify(this.data), { encoding: 'utf8' }); } /** * Get value from store * @param {string | ((data: any, fallback: any) => any)} key * @param {any} fallback */ get(key, fallback) { if (typeof key != 'string') { return this.data; } else if (typeof key == 'function') { key(this.data, fallback); } else { return this.data[key] || fallback; } } /** * Set value to store * @param {string | ((data: any) => any)} key * @param {any} value */ set(key, value) { if (typeof key == 'function') { key(this.data); } else { this.data[key] = value; } this.changed = true; return this; } } module.exports = function (name) { return new Store(name); }