var readwritecache2 = require('../readwritecache2'); var fs=require('fs'); var _data = __dirname+'/data'; var sqlitedb = require('./sqlitedb'); var sqldb = sqlitedb; //var {Client} = require('cassandra-driver'); //const cass = new Client({ // cloud: {secureConnectBundle:'secure-connect-todo.zip'}, // credentials: { // username:'jvonmitchell@gmail.com', // password:'6e9hDX8$$' // }, //}); // //async function startcass() { // await cass.connect(); // cass.execute('use todo'); //} //startcass(); module.exports.ranks=readwritecache2({ default:{}, writefreq:1000*30, readfreq:1000*60*5, delayclearonread:true, delaywriteonwrite:true, get:(key,cb)=>{ console.log('Reading ranks for',key); sqlitedb.get("SELECT json FROM rank WHERE user=?",key,(err,json)=>{ if(err) return cb(err); if(!json) return cb(); try { cb(null,JSON.parse(json.json)); } catch(e) { cb(e); } }); }, write:(key,obj,notindb,cb)=>{ //console.log('Writing ranks for',key); if(notindb) return sqlitedb.run('INSERT INTO rank (user,json) VALUES (?,?)',key,JSON.stringify(obj),cb); sqlitedb.run('UPDATE rank SET json=? WHERE user=?',JSON.stringify(obj),key,cb); } }); module.exports.journals=readwritecache2({ default:{}, get:(key,cb)=>{ var user = key.split('.')[0]; var date=key.split('.day.')[1].replace('.json',''); //var date=key.toString(); sqldb.get('Select json from day where user=? and day=?',user,date,(err,result)=>{ if(err) return cb(err); if(result) return cb(null,JSON.parse(result.json)); //cass.execute('Select json from day where user=? and day=?',[user,date]).then(result=>{ //if(result && result.rows && result.rows.length) { // //console.log({result}); // return cb(null,JSON.parse(result.rows[0].json)); //} fs.readFile(_data+'/'+key+'.json',(err,buff)=>{ if(err) return cb(); try { cb(null,JSON.parse(buff)); } catch(e) { console.log({key,buff:buff.toString(),err:e,cb}); cb(e); } }); //}); }); }, write:(key,obj,notindb,cb)=>{ var user = key.split('.')[0]; var day = key.split('.day.')[1]; var stringified=JSON.stringify(obj); //cass.execute('Insert into day (user,day,json) values (?,?,?)',[user,day,stringified]); fs.writeFile(_data+'/'+key+'.json',stringified,cb); if(notindb) { sqldb.run('INSERT into day (user,day,json) values (?,?,?)',user,day,stringified); } else { sqldb.run('UPDATE day SET json=? WHERE user=? AND day=?',stringified,user,day); } }, writefreq:1000*30, readfreq:1000*60*5, delayclearonread:true, delaywriteonwrite:true });