sleep-tracker-backend/services/sessions/sessionsModel.js

68 lines
1.6 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)
computeSession(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);
computeSession(updatedSession);
return updatedSession;
}
async function removeSession(id) {
await db('sessions')
.where({ id })
.del();
}
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));
}
}