-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserver.js
94 lines (66 loc) · 1.97 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
// Dependencies
let { Workout } = require("./models/workout.js");
const express = require('express');
const path = require('path');
const fs = require('fs');
const mongoose = require('mongoose');
// Sets up the Express App
const app = express();
const PORT = process.env.PORT||3000;
// Sets up the Express app to handle data parsing
app.use(express.urlencoded({ extended: true }));
app.use(express.json());
app.use(express.static("public"))
mongoose.connect(process.env.MONGODB_URL || "mongodb://localhost/fitness", {
useNewUrlParser: true,
useFindAndModify: false
});
// Routes
app.get('/exercise', (req, res) => res.sendFile(path.join(__dirname, '/public/exercise.html')));
app.get('/stats', (req, res) => res.sendFile(path.join(__dirname, '/public/stats.html')));
// Displays all notes
app.get('/api/workouts', (req, res) => {
Workout.find({})
.sort({ date: -1 })
.then(dbWorkouts => {
res.json(dbWorkouts);
})
.catch(err => {
res.status(400).json(err);
});
});
// Create New notes - takes in JSON input
app.post('/api/workouts', (req, res) => {
// req.body hosts is equal to the JSON post sent from the user
// This works because of our body parsing middleware
const newWorkouts = req.body;
Workout.create(newWorkouts)
.then(dbWorkouts => {
res.json(dbWorkouts);
})
.catch(err => {
res.status(400).json(err);
});
});
app.get('/api/workouts/range', (req, res) => {
Workout.find({})
.sort({ date: -1 })
.then(dbWorkouts => {
res.json(dbWorkouts);
})
.catch(err => {
res.status(400).json(err);
});
});
app.put('/api/workouts/:workoutid', (req, res) => {
const workoutid=req.params.workoutid
Workout.findByIdAndUpdate(workoutid, { $push: { exercises: req.body } },)
.then(dbWorkouts => {
res.json(dbWorkouts);
})
.catch(err => {
res.status(400).json(err);
});
});
// Starts the server to begin listening
app.listen(PORT, () => console.log(`App listening on PORT ${PORT}`));