-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
134 lines (112 loc) · 3.58 KB
/
index.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
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
const express = require('express')
const app = express()
const cors = require('cors')
require('dotenv').config()
const bodyParser = require('body-parser');
const mongoose = require('mongoose');
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true });
app.use(cors())
app.use(express.static('public'))
app.get('/', (req, res) => {
res.sendFile(__dirname + '/views/index.html');
(mongoose.connection.readyState === 1) ? status = "MongoDB online" : status = "MongoDB offline"
console.log(status)
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log('Your app is listening on port ' + listener.address().port)
})
const exSchema = new mongoose.Schema({
description: { type: String, required: true },
duration: { type: Number, required: true },
date: String,
});
const userSchema = new mongoose.Schema({
username: {type: String, required: true},
count: { type: Number },
log: [exSchema]
});
const User = mongoose.model("User", userSchema);
const Exercise = mongoose.model("Exercise", exSchema);
// create a new username
app.post('/api/users', async (req, res) => {
const userName = req.body.username;
const userExist = await User.exists({username: userName}, async (err, doc) => {
if (err) { console.log(err) }
console.log('is user exist?: ' + !!doc);
if (!!doc) {
res.json({
username: userName,
_id: doc._id
});
} else {
const newUserName = await User.create({
username: userName
});
console.log("new user has been added to database")
const doc = await User.findOne({username: userName});
res.json({
username: doc.username,
_id: doc._id
});
}
});
});
app.get('/api/users', async (req, res) => {
const doc = await User.find({}, {log: 0}).then( (users) => {
res.send(users);
});
});
app.post('/api/users/:_id/exercises', async (req, res) => {
const description = req.body.description;
const duration = parseInt(req.body.duration);
let date = new Date(req.body.date);
if(date == 'Invalid Date'){
date = new Date(Date.now());
}
const id = req.params._id;
console.log(id, description, duration, date);
const exercise = new Exercise({
description: description,
duration: duration,
date: date.toDateString(),
});
const doc = await User.findOneAndUpdate({_id: id}, {$push: {log: exercise}});
res.json({
_id: doc._id,
username: doc.username,
date: date.toDateString(),
duration: duration,
description: description
});
});
app.get('/api/users/:_id/logs', async (req, res) => {
const id = req.params._id;
const fields = { '__v': 0, 'log._id': 0 };
const doc = await User.findById({_id: id}).select(fields).then( (result) => {
if (req.query.from || req.query.to) {
let fromDate = new Date(0);
let toDate = new Date();
if (req.query.from) {
fromDate = new Date(req.query.from);
}
if (req.query.to) {
toDate = new Date(req.query.to);
}
console.log(fromDate, toDate);
fromDate = fromDate.getTime();
toDate = toDate.getTime();
console.log(fromDate, toDate);
result.log = result.log.filter( (session) => {
let sessionDate = new Date(session.date).getTime();
return sessionDate >= fromDate && sessionDate <= toDate;
});
}
if (req.query.limit) {
result.log = result.log.slice(0, req.query.limit);
}
result.count = result.log.length;
res.json(result);
});
});