From 914f6bafce3f5040e5d5fbb267a214f24eb8c726 Mon Sep 17 00:00:00 2001 From: adb Date: Thu, 1 Apr 2021 23:22:09 +0200 Subject: [PATCH] create class JsonDataStore / fix proxy --- JsonDataStore.js | 43 +++++++++++++++++++++++++++++++++++++++++++ index.js | 15 +++------------ jsonDataStore.js | 25 ------------------------- 3 files changed, 46 insertions(+), 37 deletions(-) create mode 100644 JsonDataStore.js delete mode 100644 jsonDataStore.js diff --git a/JsonDataStore.js b/JsonDataStore.js new file mode 100644 index 0000000..45e30d0 --- /dev/null +++ b/JsonDataStore.js @@ -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; + } +} \ No newline at end of file diff --git a/index.js b/index.js index 705936a..e28ebdf 100644 --- a/index.js +++ b/index.js @@ -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(); \ No newline at end of file diff --git a/jsonDataStore.js b/jsonDataStore.js deleted file mode 100644 index 0f313f0..0000000 --- a/jsonDataStore.js +++ /dev/null @@ -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; - } -} \ No newline at end of file