import * as path from 'path' import * as fs from 'fs-extra-promise' import * as assign from 'object-assign' import * as Promise from 'bluebird' import * as os from 'os' const SYSTEM_FOLDER = os.homedir() const DATA_FOLDER = path.join(SYSTEM_FOLDER, '.cobalt') const DATA_FILE_PATH = path.join(DATA_FOLDER, 'config.json') export class Storage{ public static get(): Promise { return Storage.ensureFileExists() .then(() => getData()) } public static getSync(): any { Storage.ensureFileExistsSync(); return fs.readJsonSync(DATA_FILE_PATH, { throws: false }) || {} } public static set(newData : any): Promise { return Storage.ensureFileExists() .then(() => getData()) .then(function(oldData){ let data = assign(oldData, newData) return fs.outputJsonAsync(DATA_FILE_PATH, data) }) } public static clear(): Promise { return writeEmptyConfig(); } public static reset(fields: string[]): Promise{ return Storage.ensureFileExists() .then(() => fs.readJsonAsync(DATA_FILE_PATH)) .then(config => this.removeFields(config, fields)) .then(config => fs.outputJsonAsync(DATA_FILE_PATH, config)); } private static removeFields(obj: any, fields: string[]): any{ return Object.keys(obj) .reduce((acc: any, key: string) => { if(fields.indexOf(key) < 0){ acc[key] = obj[key] } return acc }, {}) } private static ensureFileExists() { return fs.existsAsync(DATA_FILE_PATH) .then((exists) => { if (!exists) { return writeEmptyConfig(); } }); } private static ensureFileExistsSync() { const exists = fs.existsSync(DATA_FILE_PATH) if (!exists) { fs.outputJsonSync(DATA_FILE_PATH, {}); } } } function writeEmptyConfig() { return fs.outputJsonAsync(DATA_FILE_PATH, {}); } function getData() : Promise{ return fs.readJsonAsync(DATA_FILE_PATH) .then(function (data) { return data || {} }) .catch(() => { return {} }) }