f0ckv1/src/cfg.js

74 lines
1.9 KiB
JavaScript
Raw Normal View History

2016-11-22 05:26:12 +00:00
var mysql = require('mysql');
var self = Cfg.prototype;
var haDC = () => {
self.sql = mysql.createConnection(require('../cfg/mysql.json'));
self.sql.connect((err) => {
if(err) setTimeout(haDC, 2000);
});
self.sql.on('error', (err) => {
if(err.code === 'PROTOCOL_CONNECTION_LOST') haDC();
});
};
haDC();
module.exports = Cfg;
function Cfg() {
2016-11-22 06:02:40 +00:00
self.cfg;
2016-11-22 05:26:12 +00:00
}
self.read = (cb, kat, key) => {
// main, websrv, irc
2016-11-22 06:02:40 +00:00
var out = {
irc: {},
main: {},
websrv: {},
trigger: {}
};
2016-11-22 05:26:12 +00:00
self.sql.query("select * from `f0ck`.`cfg`" + (kat?" where `class` = '"+kat+"'"+(key?" && `key` = '"+key+"'":""):""), (err, rows) => {
if(err || rows.length < 1)
cb(err);
else {
rows.forEach(e => {
2016-11-22 06:02:40 +00:00
out[e.class][e.key] = ((type, value) => {
2016-11-22 05:26:12 +00:00
switch(type) {
case 'string':
return value;
break;
case 'int':
return parseInt(value);
break;
case 'bool':
return (value === 'true')?true:false;
break;
case 'json':
return JSON.parse(value);
break;
}
})(e.type, e.value);
});
if(cb)
2016-11-22 06:02:40 +00:00
cb( key?out[kat][key]:out );
else
if(!kat && !key)
self.cfg = out;
}
});
};
self.write = (kat, key, value, type, cb) => {
self.sql.query("select * from `f0ck`.`cfg` where `class` = ? && `key` = ? limit 1", [kat, key], (err, rows) => {
if(rows.length > 0) {
self.sql.query("update `f0ck`.`cfg` set `value` = ? where `class` = ? && `key` = ?", [value, kat, key], (err) => {
self.read();
if(cb) cb(err);
});
}
else {
self.sql.query("insert into `f0ck`.`cfg` (`class`,`key`,`value`,`type`) values (?,?,?,?)", [kat, key, value, type], (err) => {
self.read();
if(cb) cb(err);
});
2016-11-22 05:26:12 +00:00
}
});
};