keeweb/app/scripts/comp/settings-store.js

54 lines
1.8 KiB
JavaScript
Raw Normal View History

2015-12-05 14:57:43 +01:00
'use strict';
const Launcher = require('./launcher');
2017-01-31 07:50:28 +01:00
const StringUtil = require('../util/string-util');
const Logger = require('../util/logger');
2015-12-12 09:53:50 +01:00
2017-01-31 07:50:28 +01:00
const logger = new Logger('settings');
2015-12-05 14:57:43 +01:00
2017-01-31 07:50:28 +01:00
const SettingsStore = {
2017-02-01 02:37:43 +01:00
2015-12-05 14:57:43 +01:00
fileName: function(key) {
2017-02-04 14:17:34 +01:00
return `${key}.json`;
2015-12-05 14:57:43 +01:00
},
load: function(key, callback) {
2015-12-05 14:57:43 +01:00
try {
2017-02-04 14:17:34 +01:00
if (Launcher) {
2017-01-31 07:50:28 +01:00
const settingsFile = Launcher.getUserDataPath(this.fileName(key));
2017-02-04 14:17:34 +01:00
Launcher.fileExists(settingsFile, exists => {
if (exists) {
Launcher.readFile(settingsFile, data => {
2017-02-05 00:30:29 +01:00
const contents = typeof data === 'string' ? data : String.fromCharCode.apply(null, data);
callback(JSON.parse(contents));
}, err => { // eslint-disable-line handle-callback-err
callback(undefined);
});
2017-02-04 14:17:34 +01:00
}
});
2015-12-05 14:57:43 +01:00
} else {
2017-01-31 07:50:28 +01:00
const data = localStorage[StringUtil.camelCase(key)];
2017-02-04 14:17:34 +01:00
callback(data ? JSON.parse(data) : undefined);
2015-12-05 14:57:43 +01:00
}
} catch (e) {
2017-02-04 14:17:34 +01:00
logger.error(`Error loading ${key}`, e);
2015-12-05 14:57:43 +01:00
}
},
save: function(key, data, callback) {
2015-12-05 14:57:43 +01:00
try {
2017-02-04 14:17:34 +01:00
if (Launcher) {
const settingsFile = Launcher.getUserDataPath(this.fileName(key));
Launcher.writeFile(settingsFile, JSON.stringify(data), callback, callback);
2015-12-05 14:57:43 +01:00
} else if (typeof localStorage !== 'undefined') {
localStorage[StringUtil.camelCase(key)] = JSON.stringify(data);
callback && callback();
2015-12-05 14:57:43 +01:00
}
} catch (e) {
2017-02-04 14:17:34 +01:00
logger.error(`Error saving ${key}`, e);
2015-12-05 14:57:43 +01:00
}
}
};
module.exports = SettingsStore;