import sql from "./sql"; 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); sql.any("select * from cfg where class = $1 && key = $2 limit 1", [kat, key]).then(rows => { if (rows.length > 0) { sql.any("update cfg set value = $1 where class = $2 && key = $3", [value, kat, key]).then(rows => { read().then(() => { if(cb) cb(); }); }) .catch(err => { console.log("on update", err); }); } else { sql.any("insert into cfg (class, key, value, type) values ($1, $2, $3, $4)", [kat, key, value, type]).then(rows => { read().then(() => { if (cb) cb(); }); }) .catch(err => { console.log("on insert", err); }); } }) .then(err => { console.log("on select", err); }); }; export { cfg, read, write };