2019-08-01 14:25:44 +00:00
|
|
|
const db = require('../../data/dbConfig');
|
|
|
|
|
|
|
|
module.exports = {
|
|
|
|
addSession,
|
|
|
|
findUserSessions,
|
|
|
|
updateSession,
|
|
|
|
removeSession
|
2019-08-01 18:43:43 +00:00
|
|
|
}
|
2019-08-01 14:25:44 +00:00
|
|
|
|
|
|
|
async function addSession(session) {
|
|
|
|
const [id] = await db('sessions')
|
|
|
|
.insert(session);
|
2019-08-01 18:43:43 +00:00
|
|
|
|
|
|
|
const newSession = await findSessionById(id)
|
|
|
|
computeSession(newSession);
|
|
|
|
return newSession;
|
2019-08-01 14:25:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
function findUserSessions(user_id) {
|
|
|
|
return db
|
|
|
|
.from("sessions")
|
|
|
|
.where({ user_id });
|
|
|
|
}
|
|
|
|
|
|
|
|
function findSessionById(id) {
|
|
|
|
return db('sessions')
|
|
|
|
.where({ id })
|
|
|
|
.first();
|
|
|
|
}
|
|
|
|
|
|
|
|
async function updateSession(id, changes) {
|
|
|
|
await db('sessions')
|
|
|
|
.where({ id })
|
|
|
|
.update(changes, '*');
|
2019-08-01 18:43:43 +00:00
|
|
|
const updatedSession = await findSessionById(id);
|
|
|
|
computeSession(updatedSession);
|
|
|
|
return updatedSession;
|
2019-08-01 14:25:44 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function removeSession(id) {
|
|
|
|
await db('sessions')
|
|
|
|
.where({ id })
|
|
|
|
.del();
|
2019-08-01 18:43:43 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
async function computeSession(session) {
|
|
|
|
if ( session.bed_tiredness && session.day_mood && session.wake_mood) {
|
|
|
|
// Calculate the sleep duration
|
|
|
|
let date1 = new Date(session.bed_time);
|
|
|
|
let date2 = new Date(session.wake_time);
|
|
|
|
let diffTime = Math.abs(date1.getTime() - date2.getTime());
|
|
|
|
diffTime = diffTime/(1000*60*60);
|
|
|
|
let sleep_duration = Math.round( diffTime * 100) / 100;
|
|
|
|
|
|
|
|
// Calculate the average mood
|
|
|
|
let average_mood = (session.bed_tiredness + session.wake_mood + session.day_mood) / 3;
|
|
|
|
let new_average_mood = Math.round( average_mood * 100) / 100;
|
|
|
|
|
|
|
|
await db('dailyAverages')
|
|
|
|
.insert({
|
|
|
|
session_id: session.id,
|
|
|
|
user_id: session.user_id,
|
|
|
|
sleep_duration: sleep_duration,
|
|
|
|
average_mood: new_average_mood,
|
|
|
|
})
|
|
|
|
.catch(err => console.log(err));
|
|
|
|
}
|
2019-08-01 14:25:44 +00:00
|
|
|
}
|