Lightcord/modules/discord_desktop_core/core/common/Settings.js

75 lines
1.7 KiB
JavaScript
Raw Normal View History

2020-12-12 11:56:28 +01:00
"use strict";
2020-05-16 23:24:51 +02:00
Object.defineProperty(exports, "__esModule", {
value: true
});
2020-12-12 11:56:28 +01:00
exports.default = void 0;
2020-05-16 23:24:51 +02:00
2020-12-12 11:56:28 +01:00
var _fs = _interopRequireDefault(require("fs"));
2020-05-16 23:24:51 +02:00
2020-12-12 11:56:28 +01:00
var _path = _interopRequireDefault(require("path"));
2020-05-16 23:24:51 +02:00
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
// TODO: sync fs operations could cause slowdown and/or freezes, depending on usage
// if this is fine, remove this todo
class Settings {
constructor(root) {
2020-12-12 11:56:28 +01:00
this.path = _path.default.join(root, 'settings.json');
2020-05-16 23:24:51 +02:00
try {
2020-12-12 11:56:28 +01:00
this.lastSaved = _fs.default.readFileSync(this.path);
2020-05-16 23:24:51 +02:00
this.settings = JSON.parse(this.lastSaved);
} catch (e) {
this.lastSaved = '';
this.settings = {};
}
2020-12-12 11:56:28 +01:00
2020-05-16 23:24:51 +02:00
this.lastModified = this._lastModified();
}
_lastModified() {
try {
2020-12-12 11:56:28 +01:00
return _fs.default.statSync(this.path).mtime.getTime();
2020-05-16 23:24:51 +02:00
} catch (e) {
return 0;
}
}
get(key, defaultValue = false) {
if (this.settings.hasOwnProperty(key)) {
return this.settings[key];
}
return defaultValue;
}
set(key, value) {
this.settings[key] = value;
}
save() {
if (this.lastModified && this.lastModified !== this._lastModified()) {
console.warn('Not saving settings, it has been externally modified.');
return;
}
try {
const toSave = JSON.stringify(this.settings, null, 2);
2020-12-12 11:56:28 +01:00
2020-05-16 23:24:51 +02:00
if (this.lastSaved != toSave) {
this.lastSaved = toSave;
2020-12-12 11:56:28 +01:00
_fs.default.writeFileSync(this.path, toSave);
2020-05-16 23:24:51 +02:00
this.lastModified = this._lastModified();
}
} catch (err) {
console.warn('Failed saving settings with error: ', err);
}
}
2020-12-12 11:56:28 +01:00
2020-05-16 23:24:51 +02:00
}
2020-12-12 11:56:28 +01:00
2020-05-16 23:24:51 +02:00
exports.default = Settings;
module.exports = exports.default;