Repository navigation
Expand file tree
/
Copy pathserver.js
More file actions
98 lines (82 loc) · 2.26 KB
/
Copy pathserver.js
File metadata and controls
98 lines (82 loc) · 2.26 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
const path = require("path");
const express = require("express");
const mongoose = require("mongoose");
require('dotenv').config();
const PORT = process.env.PORT || 3000;
const db = require("./models");
const app = express();
mongoose.connect(process.env.MONGODB_URI || "mongodb://localhost/workout",
{
useNewUrlParser: true,
useUnifiedTopology: true,
useCreateIndex: true,
useFindAndModify: false
})
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"));
//ROUTES~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
// api/workouts
//CREATE ROUTES
app.post("/api/workouts", ({ body }, res) => {
db.Workout.create(body)
.then(workout => {
res.json(workout);
})
.catch(err => {
res.json(err);
});
})
// READ ROUTES
app.get("/api/workouts", (req,res) => {
db.Workout.aggregate([{
$addFields: {
totalDuration: { $sum: "$exercises.duration" }
}
}])
.then(workout => {
res.json(workout);
})
.catch(err => {
res.json(err);
});
})
app.get("/api/workouts/range", (req,res) => {
db.Workout.aggregate([
{
$addFields: {
totalWeight: { $sum: "$exercises.weight" },
totalDuration: { $sum: "$exercises.duration" }
}
}])
.then(workout => {
res.json(workout);
})
.catch(err => {
res.json(err);
});
})
app.get("/exercise", (req, res) => {
res.sendFile(path.join(__dirname, "public/exercise.html"));
});
app.get("/stats", (req, res) => {
res.redirect("/stats.html");
});
// UPDATE ROUTES
app.put("/api/workouts/:id", (req,res) => {
db.Workout.updateOne(
{ _id: req.params.id },
{ $push: { exercises: req.body } },
(error, success) => {
if (error) {
res.json(error);
} else {
res.json(success);
}
}
);
})
// Listen on port PORT
app.listen(PORT, () => {
console.log(`App running on port ${PORT}!`);
});