Fix dailyAverages query on session update & test
- Add dailyAverages seeds - Start implementing testing
This commit is contained in:
@@ -12,7 +12,7 @@ async function addSession(session) {
|
||||
.insert(session);
|
||||
|
||||
const newSession = await findSessionById(id)
|
||||
computeSession(newSession);
|
||||
addDailyAverage(newSession);
|
||||
return newSession;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ async function updateSession(id, changes) {
|
||||
.where({ id })
|
||||
.update(changes, '*');
|
||||
const updatedSession = await findSessionById(id);
|
||||
computeSession(updatedSession);
|
||||
updateDailyAverage(id, updatedSession);
|
||||
return updatedSession;
|
||||
}
|
||||
|
||||
@@ -43,7 +43,8 @@ async function removeSession(id) {
|
||||
.del();
|
||||
}
|
||||
|
||||
async function computeSession(session) {
|
||||
//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);
|
||||
@@ -65,4 +66,29 @@ async function computeSession(session) {
|
||||
})
|
||||
.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));
|
||||
}
|
||||
}
|
||||
@@ -2,6 +2,7 @@ const router = require('express').Router();
|
||||
|
||||
const Sessions = require('../sessions/sessionsModel');
|
||||
|
||||
// TODO: add validation
|
||||
router.post('/sessions', (req, res) => {
|
||||
Sessions.addSession(req.body)
|
||||
.then(response => {
|
||||
|
||||
Reference in New Issue
Block a user