-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
211 lines (191 loc) · 5.78 KB
/
server.js
File metadata and controls
211 lines (191 loc) · 5.78 KB
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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
require('dotenv').config();
const express = require('express');
const app = express();
const bodyParser = require('body-parser');
const shortid= require('shortid');
const cors = require('cors');
const User = require('./models/user');
const Exercise = require('./models/exercise');
const mongoose = require('mongoose');
// let url = 'mongodb://localhost/exerciseTracker';
let url = process.env.MONGODB_URI;
mongoose.connect(url, { useUnifiedTopology: true, useNewUrlParser: true });
app.use(cors());
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
app.use(express.static('public'))
app.post('/api/exercise/new-user', (req, res)=>{
const username = req.body.username;
let newUser = new User({
username: username,
})
//Checking if user already exist or not
User.findOne({ username: username }, (err, user)=>{
if(err){
console.error(err);
return res.redirect('/');
}
if(user) return res.send("Username alerady taken");
else{
// if user doesn't exist then create a new user
User.create(newUser, (err, user)=>{
console.log("New User Created", user);
res.json({ username: user.username, _id: user._id });
});
}
});
});
app.post('/api/exercise/add', (req, res)=>{
let newExercise = new Exercise({
description: req.body.description,
duration: req.body.duration
});
if(req.body.date){
newExercise.date = new Date(req.body.date)
}else{
newExercise.date = new Date();
}
// Checking if the user exist for which new exercise is created
User.findById(req.body.userId, (err, user)=>{
if(err){
console.error(err);
return res.redirect('/');
}
if(!user) return res.send("User Does Not Exist");
// Since the user exist we will create a exercise
Exercise.create(newExercise, (err, exercise)=>{
if(err){
console.error(err);
return res.redirect('/');
}
console.log("New Exercise Created", exercise);
user.logs.push(exercise);
// user.count = user.logs.length;
user.save();
res.json({
_id: user._id,
username: user.username,
date: exercise.date.toDateString(),
duration: exercise.duration,
description: exercise.description
});
});
});
});
app.get('/api/exercise/users', (req, res)=>{
User.find({}, (err, users)=>{
if(err) {
console.error(err);
res.redirect('/');
}
if(!users) return res.send("No Users Found");
let result = [];
users.forEach((user)=>{
result.push(user.username);
})
res.send(result);
})
})
app.get('/api/exercise/log', (req, res)=>{
let userId = req.query.userId;
let from = req.query.from;
let to = req.query.to;
let limit = req.query.limit;
if(limit) limit = parseInt(limit);
User.findById(userId).populate("logs").exec((err, user)=>{
if(err){
console.error(err);
return res.redirect('/');
}
if(!user){
return res.send("User Doesn't exist");
}
let result = {};
result._id = user._id;
result.username = user.username;
result.count = 0;
result.log = [];
// If there is no query of from and to
if(!from && !to){
if((limit && limit > 0) || !limit){
user.logs.forEach((log, i)=>{
if(limit && result.log.length >= limit) return;
let temp = {};
temp.description = log.description;
temp.duration = log.duration;
temp.date = log.date.toDateString();
result.log.push(temp);
})
result.count = result.log.length;
return res.json(result);
}
return res.json(result);
}
// If there exist a from query
if(from){
from = new Date(from).getTime();
// If there is a limit query > 0 or not any query
if((limit && limit > 0) || !limit){
user.logs.forEach((log, i)=>{
if(from > log.date.getTime() || (limit && result.log.length >= limit)) return;
// If there exist a to query along with the from query
if(to){
to = new Date(to).getTime();
if(to < log.date.getTime() || to < from) return;
}
let temp = {};
temp.description = log.description;
temp.duration = log.duration;
temp.date = log.date.toDateString();
result.log.push(temp);
})
result.count = result.log.length;
return res.json(result);
}
res.json(result);
}
// If there is a to query without a from query
else if(to){
to = new Date(to).getTime();
if((limit && limit > 0) || !limit){
user.logs.forEach((log, i)=>{
if(to < log.date.getTime() || (limit && result.log.length >= limit)) return;
let temp = {};
temp.description = log.description;
temp.duration = log.duration;
temp.date = log.date.toDateString();
result.log.push(temp);
})
return res.json(result);
}
return res.json(result);
}
})
})
app.get('/*', (req, res) => {
res.sendFile(__dirname + '/views/index.html')
});
// Not found middleware
app.use((req, res, next) => {
return next({status: 404, message: 'Page not found'})
});
// Error Handling middleware
app.use((err, req, res, next) => {
let errCode, errMessage
if (err.errors) {
// mongoose validation error
errCode = 400 // bad request
const keys = Object.keys(err.errors)
// report the first validation error
errMessage = err.errors[keys[0]].message
} else {
// generic or custom error
errCode = err.status || 500
errMessage = err.message || 'Internal Server Error'
}
res.status(errCode).type('txt')
.send(errMessage)
})
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})