var cmn=require("../$common.js"); var persist=require("node-persist"), util=require("util"); //Sorry. Prototypes are fun. Using dollars to at least separate these from the built-in methods. Date.prototype.$dayOfWeek=function(){return (this.getDay()+6)%7;} //monday..sunday = 0..6 Date.prototype.$startOfDay=function(){return new Date(this-(((this.getHours()*60+this.getMinutes())*60+this.getSeconds())*1000+this.getMilliseconds()));} Date.prototype.$addDays=function(n){return new Date(this.valueOf()+n*24*3600*1000);} Date.prototype.$addWeeks=function(n){return new Date(this.valueOf()+n*7*24*3600*1000);} Date.prototype.$naturalDate=function(){return this.getFullYear()+"-"+("00"+(this.getMonth()+1)).slice(-2)+"-"+("00"+this.getDate()).slice(-2);} function diffDays(d1,d2){return ~~(Math.abs(d1-d2)/1000/3600/24);} function localDateStringToDate(s){return new Date(s+"T00:00:00");} var periodStart="2015-04-09",periodEnd="2015-07-05", periodLength=diffDays(localDateStringToDate(periodStart),localDateStringToDate(periodEnd))+1; persist=persist.create({ dir:cmn.persistdir+"/datumpjeprik", continuous:false, interval:false }); persist.initSync(); function ensureInitialised(){ var days; days=persist.getItem("days"); if(!days||days.length!=periodLength){ days=Array.apply(null,new Array(periodLength)).map(function(){return 0;}); persist.setItemSync("days",days); } } ensureInitialised(); module.exports=function(app,io,moddir){ app.get("/datumpjeprik",function(req,res){ res.set("Content-Type","text/html"); res.sendFile(moddir+"/datumpjeprik.html"); }); app.get("/datumpjeprik/dates",function(req,res){ res.set("Content-Type","text/json"); res.send('{"periodStart":"'+periodStart+'","periodEnd":"'+periodEnd+'"}'); }); app.get("/datumpjeprik/days",function(req,res){ ensureInitialised(); res.set("Content-Type","text/json"); res.send(persist.getItem("days")); }); app.post("/datumpjeprik/adddays",function(req,res){ var newdays; console.log(req.body); try{ newdays=JSON.parse(req.body); if(newdays.length!=periodLength)throw new Error("length mismatch"); if(!newdays.map(function(v){return typeof v=="boolean";}).reduce(function(a,b){return a&&b;}))throw new Error("not all bools"); ensureInitialised(); persist.setItemSync("days",persist.getItem("days").map(function(v,i){return v+newdays[i];})); res.send("true"); } catch(e){ res.send("[false,\""+e.message+"\"]"); return; } }); };