create class JsonDataStore / fix proxy

master
adb 4 years ago
parent 5d966f422a
commit 914f6bafce

@ -0,0 +1,43 @@
import fs from "fs";
export class JsonDataStore {
constructor(path) {
this.path = path;
this.data = this.loadData(path);
this.proxyHandler = {
set: (target, key, value) => {
console.log(`config changed: ${key} set from ${target[key]} to ${value}`);
target[key] = value;
this.storeData(this.data);
return true;
},
get: (target, key) => {
if (typeof target[key] === 'object') return new Proxy(target[key], this.proxyHandler);
return target[key];
}
};
this.proxy = new Proxy(this.data, this.proxyHandler);
}
storeData(data, path = this.path) {
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
}
}
loadData(path = this.path) {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'));
} catch (err) {
console.error(err);
return false;
}
}
getData(){
return this.data;
}
getSyncedData(){
return this.proxy;
}
}

@ -1,16 +1,7 @@
import {DynDnsBot} from './DynDnsBot.js';
import {loadData, storeData} from './jsonDataStore.js';
import {JsonDataStore} from './JsonDataStore.js';
let configPath = 'config.json';
let config = loadData(configPath);
let store = new JsonDataStore('config.json');
let configProxy = new Proxy(config, {
set: (target, key, value) => {
console.log(`config changed: ${key} set from ${target[key]} to ${value}`);
target[key] = value;
storeData(config, configPath);
return true;
}
});
let bot = new DynDnsBot({config: configProxy});
let bot = new DynDnsBot({config: store.getSyncedData()});
bot.setInterval();

@ -1,25 +0,0 @@
import fs from "fs";
export function storeData(data, path) {
try {
fs.writeFileSync(path, JSON.stringify(data));
} catch (err) {
console.error(err);
}
}
export function loadData(path) {
try {
return JSON.parse(fs.readFileSync(path, 'utf8'))
} catch (err) {
console.error(err)
return false
}
}
export function getStat(path) {
try {
return fs.existsSync(path) === true;
} catch(err) {
console.error(err)
return false;
}
}
Loading…
Cancel
Save