-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
112 lines (92 loc) · 2.52 KB
/
app.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
const express = require("express");
const app = express();
const moment = require('moment');
const router = express.Router();
const User = require("./userModel");
router.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
router.get("/sayHello", (req, res) => {
res.send("Hello");
});
router.get("/api/exercise/users", (req, res) => {
User.find()
.then(users => {
let usersArr = [];
users.forEach(user => {
usersArr.push({
user: user.username,
exercises:
user.exercises.length === 0
? "No exercises listed yet"
: user.exercises
});
});
res.send(usersArr);
})
.catch(err => console.error(err));
});
router.get("/api/exercise/log", (req, res) => {
const user = req.query.userId;
const from = req.query.from;
const to = req.query.to;
const limit = req.querty.limit;
console.log(user);
User.findById(user, (err, userData) => {
let userExercises = [];
if(err) res.send(`User not found`);
if(from && to){
userExercises = userData.filter(exercise => {
exercise.date >= from && exercise.date <= to;
});
} else if (from) {
userExercises = userData.filter(exercise => {
exercise.date >= from;
});
};
if ( userData.exercises.length > limit ) {
userExercises = userExercises.slice( 0, limit );
}
res.send({
user: user.username,
total: userExercises.length,
exercise: userExercises
});
res.send(userData);
});
});
router.post("/api/exercise/new-user", (req, res) => {
const username = req.body.username;
const newUser = new User({ username });
newUser
.save()
.then(user => {
console.log(`${username} has been saved with id: ${user.id}`);
res.json({ username, id: user.id });
})
.catch(err => {
res.send(`${username} has already been taken`);
});
});
router.post("/api/exercise/add", (req, res) => {
const userId = req.body.userId;
const date = moment().format('YYYY-MM-DD');
const update = {
description: req.body.description,
duration: req.body.duration,
date: req.body.date || date
};
User.findByIdAndUpdate(
{ _id: userId },
{ $push: { exercises: [update] } },
{ new: true, upsert: true },
(err, user) => {
if (err) return console.error(err);
res.json({
user: user.username,
exercises: user.exercises
});
}
);
});
module.exports = router;