import sql from "./sql.js"; let cfg = { client: {}, main: {}, websrv: {}, trigger: {} }; const read = () => new Promise((resolve, reject) => { sql.any("select * from cfg").then(rows => { for (let row in rows) { cfg[rows[row].class][rows[row].key] = { val: ((type, value) => { switch (type) { case "string": return value; case "int": return parseInt(value); case "bool": return value === "true"; case "json": return JSON.parse(value); } })(rows[row].type, rows[row].value), hidden: rows[row].hidden === 1, type: rows[row].type } } resolve(); }) .catch(err => { reject("no cfg"); }) }); const write = (kat, key, value, type, cb) => { if (type === "json") value = JSON.stringify(value); console.log(kat, key, value, type); sql.any("select * from cfg where class = ? && key = ? limit 1", [kat, key], (err, rows) => { console.log(rows); if (rows.length > 0) { sql.any("update cfg set value = ? where class = ? && key = ?", [value, kat, key], (err) => { console.log("updated", err); read().then(() => { if(cb) cb(); }); }); } else { sql.any("insert into cfg (class, key, value, type) values (?, ?, ?, ?)", [kat, key, value, type], (err) => { console.log("inserted", err); read().then(() => { if (cb) cb(); }); }); } }); }; export { cfg, read, write };