-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
251 lines (220 loc) · 6.52 KB
/
server.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
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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
const express = require("express");
const app = express();
const cors = require("cors");
require("dotenv").config();
// * DB Packages
const mongodb = require("mongodb");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
// * MongoDB connection
mongoose.connect(process.env.MONGODB_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false,
});
// * MongoDB connection confirmation and error handling
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", () => console.log("MongoDB connection established \n"));
// * Exercise Schema
const exerciseSchema = new Schema({
date: { type: Date },
duration: { type: Number },
description: { type: String },
});
// * User Schema
const usersSchema = new Schema({
username: {
type: String,
required: true,
unique: true,
},
count: {
type: Number,
},
log: [exerciseSchema],
});
// * Model
const Exercise = mongoose.model("Exercise", exerciseSchema);
const User = mongoose.model("User", usersSchema);
app.use(express.urlencoded({ extended: false }));
app.use(express.json());
app.use(cors());
app.use(express.static("public"));
app.get("/", (req, res) => {
res.sendFile(__dirname + "/views/index.html");
});
/*====================================================
// ! To Remove All Collection
======================================================*/
// async function removeCollections() {
// await User.find();
// await User.remove();
// console.log("All Collections Removed From DB");
// }
// removeCollections();
/*=====================================================*/
// hello API
app.get("/hello", (req, res) => {
console.log("hello");
res.send("hello there");
});
/*
? TEST 2
* You can POST to /api/users with form data username to create a
* new user. The returned response will be an object with username
* and _id properties.
*/
app.post("/api/users", (req, res) => {
if (req.body.username === "") {
res.json({ error: "Please enter username" });
} else {
let searchUser = User.findOne(
{ username: req.body.username },
(err, searchResult) => {
if (searchResult) {
res.json({ error: "Username already taken" });
} else {
let newUser = new User({
username: req.body.username,
});
newUser.save();
res.json({
_id: newUser._id,
username: newUser.username,
});
}
}
);
}
});
/*
? TEST 3
* You can make a GET request to /api/users to get an array
* of all users. Each element in the array is an object
* containing a user's username and _id.
*/
app.get("/api/users", async (req, res) => {
await User.find({}, (err, resultDocs) => {
if (err) {
console.error(err);
res.send(err);
} else {
res.json(resultDocs);
}
});
});
/*
? TEST 4
* You can POST to /api/users/:_id/exercises with form data
* description, duration, and optionally date. If no date is
* supplied, the current date will be used. The response returned
* will be the user object with the exercise fields added.
*/
app.post("/api/users/:_id/exercises", (req, res) => {
var newExercise = {
date: req.body.date,
duration: parseInt(req.body.duration),
description: req.body.description,
};
if (!req.body.date) {
newExercise.date = new Date();
}
User.findByIdAndUpdate(
req.params._id,
{ $push: { log: newExercise } },
{ new: true },
(err, userUpdate) => {
if (err) {
console.error(err);
res.send(err);
} else {
if (!userUpdate) {
res.json({
error: "_id does not exist",
});
} else {
let newExerciseApiObj = {
username: userUpdate.username,
description: newExercise.description,
duration: newExercise.duration,
_id: userUpdate._id,
date: new Date(newExercise.date).toDateString(),
};
res.json(newExerciseApiObj);
}
}
}
);
});
/*
? TEST 5.1
* You can make a GET request to /api/users/:_id/logs to retrieve a
* full exercise log of any user. The returned response will be the user
* object with a log array of all the exercises added. Each log item has
* the description, duration, and date properties.
? TEST 5.2
* A request to a user's log (/api/users/:_id/logs) returns an object
* with a count property representing the number of exercises returned.
? TEST 5.3
* You can add from, to and limit parameters to a /api/users/:_id/logs
* request to retrieve part of the log of any user. from and to are dates
* in yyyy-mm-dd format. limit is an integer of how many logs to send back.
*/
app.get("/api/users/:_id/logs", (req, res) => {
let userId = req.params._id;
// let from;
// let to;
// let limit;
User.findById(userId, (err, searchResult) => {
if (err) {
res.json({
error: "_id does not exist",
});
} else {
// *getting query string parameters if they are given
if (req.query.from) {
from = new Date(req.query.from).getTime();
}
if (req.query.to) {
to = new Date(req.query.to).getTime();
}
/*
* Filter of Array will be done using the EPOCH date
*/
if (req.query.from !== undefined && req.query.to !== undefined) {
searchResult.log = searchResult.log.filter((filteredLogs) => {
let exerciseDate = new Date(filteredLogs.date).getTime();
return exerciseDate >= from && exerciseDate <= to;
});
}
if (req.query.from !== undefined) {
searchResult.log = searchResult.log.filter((filteredLogs) => {
let exerciseDate = new Date(filteredLogs.date).getTime();
return exerciseDate >= from;
});
}
if (req.query.to !== undefined) {
searchResult.log = searchResult.log.filter((filteredLogs) => {
let exerciseDate = new Date(filteredLogs.date).getTime();
return exerciseDate <= to;
});
}
// * limiting the results of filtered logs
if (req.query.limit !== undefined) {
limit = req.query.limit;
searchResult.log = searchResult.log.slice(0, limit);
}
res.json({
_id: searchResult._id,
username: searchResult.username,
count: searchResult.log.length,
log: searchResult.log,
});
}
});
});
const listener = app.listen(process.env.PORT || 3000, () => {
console.log("Your app is listening on port " + listener.address().port);
});