Fix dailyAverages query on session update & test

- Add dailyAverages seeds
- Start implementing testing
This commit is contained in:
ruihildt 2019-08-02 01:18:56 +02:00
parent 7bddb9a54e
commit 77a4c28757
12 changed files with 180 additions and 24 deletions

View File

@ -1,17 +1,19 @@
module.exports = { module.exports = {
"env": { "env": {
"commonjs": true, "commonjs": true,
"es6": true, "es6": true,
"node": true "node": true,
}, jest: true
"extends": "eslint:recommended", },
"globals": { "extends": "eslint:recommended",
"Atomics": "readonly", "globals": {
"SharedArrayBuffer": "readonly" "Atomics": "readonly",
}, "SharedArrayBuffer": "readonly"
"parserOptions": { },
"ecmaVersion": 2018 "parserOptions": {
}, "ecmaVersion": 2018
"rules": { },
} "rules": {
semi: 1
}
}; };

View File

@ -3,6 +3,6 @@ require("dotenv").config();
const knex = require('knex'); const knex = require('knex');
const config = require('../knexfile'); const config = require('../knexfile');
const environment = process.env.DB_ENV || 'development'; const environment = process.env.DB_ENV || 'test';
module.exports = knex(config[environment]); module.exports = knex(config[environment]);

View File

@ -52,6 +52,7 @@ exports.up = function(knex) {
.unsigned() .unsigned()
.notNullable() .notNullable()
.references('sessions.id') .references('sessions.id')
.unique()
.onUpdate('CASCADE') .onUpdate('CASCADE')
.onDelete('CASCADE'); .onDelete('CASCADE');
tbl tbl
@ -66,7 +67,7 @@ exports.up = function(knex) {
.unsigned(); .unsigned();
tbl tbl
.float('average_mood'); .float('average_mood');
}) });
}; };
exports.down = function(knex) { exports.down = function(knex) {

View File

@ -0,0 +1,77 @@
exports.seed = function(knex) {
return knex('dailyAverages').truncate()
.then(function () {
return knex('dailyAverages').insert([
{
"id": 1,
"session_id": 1,
"user_id": 1,
"sleep_duration": 9,
"average_mood": 3
},
{
"id": 2,
"session_id": 2,
"user_id": 1,
"sleep_duration": 7.67,
"average_mood": 4
},
{
"id": 3,
"session_id": 3,
"user_id": 1,
"sleep_duration": 7.67,
"average_mood": 4
},
{
"id": 4,
"session_id": 4,
"user_id": 1,
"sleep_duration": 6.67,
"average_mood": 3
},
{
"id": 5,
"session_id": 5,
"user_id": 1,
"sleep_duration": 9.5,
"average_mood": 4
},
{
"id": 6,
"session_id": 6,
"user_id": 1,
"sleep_duration": 7.5,
"average_mood": 4
},
{
"id": 7,
"session_id": 7,
"user_id": 1,
"sleep_duration": 8.58,
"average_mood": 2.67
},
{
"id": 8,
"session_id": 8,
"user_id": 1,
"sleep_duration": 8.42,
"average_mood": 4.33
},
{
"id": 9,
"session_id": 9,
"user_id": 1,
"sleep_duration": 6.25,
"average_mood": 3.33
},
{
"id": 10,
"session_id": 10,
"user_id": 1,
"sleep_duration": 11.25,
"average_mood": 3.67
}
]);
});
};

Binary file not shown.

View File

@ -5,7 +5,10 @@
"main": "index.js", "main": "index.js",
"scripts": { "scripts": {
"start": "node index.js", "start": "node index.js",
"test": "node test" "test": "jest --watch"
},
"jest": {
"testEnvironment": "node"
}, },
"repository": { "repository": {
"type": "git", "type": "git",

View File

@ -2,9 +2,9 @@ const db = require('../../data/dbConfig');
module.exports = { module.exports = {
getDailyAverages getDailyAverages
} };
function getDailyAverages(id) { function getDailyAverages(id) {
return db('dailyAverages') return db('dailyAverages')
.where({ id }); .where({user_id : id });
} }

View File

@ -4,7 +4,7 @@ const router = require('express').Router();
const Averages = require('./dailyAveragesModel'); const Averages = require('./dailyAveragesModel');
router.get('/:id/averages', (req, res) => { router.get('/:id/averages', (req, res) => {
Averages.getDailyAverages(req.params.id) Averages.getDailyAverages(req.params.id)
.then(averages => { .then(averages => {
res.status(200).json(averages); res.status(200).json(averages);
}) })

View File

@ -12,7 +12,7 @@ async function addSession(session) {
.insert(session); .insert(session);
const newSession = await findSessionById(id) const newSession = await findSessionById(id)
computeSession(newSession); addDailyAverage(newSession);
return newSession; return newSession;
} }
@ -33,7 +33,7 @@ async function updateSession(id, changes) {
.where({ id }) .where({ id })
.update(changes, '*'); .update(changes, '*');
const updatedSession = await findSessionById(id); const updatedSession = await findSessionById(id);
computeSession(updatedSession); updateDailyAverage(id, updatedSession);
return updatedSession; return updatedSession;
} }
@ -43,7 +43,8 @@ async function removeSession(id) {
.del(); .del();
} }
async function computeSession(session) { //TODO: Refactor code
async function addDailyAverage(session) {
if ( session.bed_tiredness && session.day_mood && session.wake_mood) { if ( session.bed_tiredness && session.day_mood && session.wake_mood) {
// Calculate the sleep duration // Calculate the sleep duration
let date1 = new Date(session.bed_time); let date1 = new Date(session.bed_time);
@ -65,4 +66,29 @@ async function computeSession(session) {
}) })
.catch(err => console.log(err)); .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));
}
} }

View File

@ -2,6 +2,7 @@ const router = require('express').Router();
const Sessions = require('../sessions/sessionsModel'); const Sessions = require('../sessions/sessionsModel');
// TODO: add validation
router.post('/sessions', (req, res) => { router.post('/sessions', (req, res) => {
Sessions.addSession(req.body) Sessions.addSession(req.body)
.then(response => { .then(response => {

View File

@ -0,0 +1,45 @@
const db = require('../../data/dbConfig');
const Users = require('./usersModel');
beforeEach(async () => {
await db('users').truncate();
});
describe('Users.addUser', () => {
it('is able to insert user to the db', async () => {
await Users.addUser({
email: "gabetest@ls.com",
username: "gabetest",
password: "1234"
});
await Users.addUser({
email: "gabetest2@ls.com",
username: "gabetest2",
password: "1234"
});
let users = await Users.findUserById(2);
expect(users.username).toBe('gabetest2');
});
// it('is only able to insert user as a string', async () => {
// let users = await Users.addUser({ username: 13 });
// let user = await Users.findUserById(1);
// expect(user.name).toBe('13');
// });
});
// describe('Users.remove', () => {
// it('is able to remove an user', async () => {
// await Users.insert({ name: 'dragon' });
// await Users.insert({ name: 'phoenix' });
// let users = await Users.get();
// users = await Users.remove(2);
// users = await Users.get();
// expect(users).toHaveLength(1);
// expect(users[0].name).toBe('dragon');
// });
// });

View File

@ -2,6 +2,7 @@ const router = require('express').Router();
const Users = require('../users/usersModel'); const Users = require('../users/usersModel');
// TODO: add validation
router.get('/:id', (req, res) => { router.get('/:id', (req, res) => {
Users.findUserById(req.params.id) Users.findUserById(req.params.id)
.then(users => { .then(users => {