sleep-tracker-backend/services/sessions/sessionsModel.js
ruihildt 77a4c28757 Fix dailyAverages query on session update & test
- Add dailyAverages seeds
- Start implementing testing
2019-08-02 01:18:56 +02:00

94 lines
2.4 KiB
JavaScript

const db = require('../../data/dbConfig');
module.exports = {
addSession,
findUserSessions,
updateSession,
removeSession
}
async function addSession(session) {
const [id] = await db('sessions')
.insert(session);
const newSession = await findSessionById(id)
addDailyAverage(newSession);
return newSession;
}
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, '*');
const updatedSession = await findSessionById(id);
updateDailyAverage(id, updatedSession);
return updatedSession;
}
async function removeSession(id) {
await db('sessions')
.where({ id })
.del();
}
//TODO: Refactor code
async function addDailyAverage(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));
}
}
async function updateDailyAverage(id, 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')
.where({ session_id: id })
.update({
session_id: session.id,
user_id: session.user_id,
sleep_duration: sleep_duration,
average_mood: new_average_mood,
}, '*')
.catch(err => console.log(err));
}
}