-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
254 lines (224 loc) · 7.61 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
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
252
253
254
const express = require('express');
const morgan = require('morgan');
const mongoose = require('mongoose');
const bodyParser = require("body-parser");
const Models = require('./models.js');
const Movies = Models.Movie;
const Users = Models.User;
// const uuid = require("uuid");
const app = express();
mongoose.connect(process.env.CONNECTION_URI, {
useNewUrlParser: true,
useUnifiedTopology: true
});
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// middleware
app.use(morgan('common'));
app.use(express.static('public'));
const cors = require('cors');
app.use(cors());
let auth = require('./auth')(app); //This ensures that Express is available in your “auth.js” file as well.
const passport = require('passport');
require('./passport');
const { check, validationResult } = require('express-validator');
// GET requests
app.get('/', (req, res) => {
res.send('Welcome to myFlix App');
});
//Reading document.html file
app.get('/documentation', (req, res) => {
res.sendFile('public/documentation.html', { root: __dirname });
});
// Gets the list of data about ALL movies, passport.authenticate('jwt', { session: false }),
app.get('/movies', passport.authenticate('jwt', { session: false }), (req, res) => {
Movies.find()
.then((movies) => {
res.status(201).json(movies);
})
.catch((err) => {
console.error(err);
res.status(500).send("Error: " +err);
})
});
// Gets the data about a single movie, by title
app.get('/movies/:title', passport.authenticate('jwt',{session: false}), (req, res) => {
res.json(movies.find( (movie) => {
return movie.title === req.params.title
}));
});
//Return data about a genre (description) by name/title (e.g., “Thriller”)
app.get('/movies/:title/genre', passport.authenticate('jwt',{session: false}), (req, res) => {
res.send('Successful GET request returning data about a genre.');
});
//Return data about a director (bio, birth year, death year) by name
app.get('/movies/directors/:name', passport.authenticate('jwt',{session: false}), (req, res) => {
res.send('Successful GET request returning data about a director.');
});
// Get all users
app.get('/users', passport.authenticate('jwt',{session: false}), (req, res) => {
Users.find()
.then((users) => {
res.status(201).json(users);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
// Get a user by username
app.get('/users/:Username', passport.authenticate('jwt',{session: false}), (req, res) => {
Users.findOne({ Username: req.params.Username })
.then((user) => {
res.json(user);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
//New users to register
app.post('/users',
// Validation logic here for request
//you can either use a chain of methods like .not().isEmpty()
//which means "opposite of isEmpty" in plain english "is not empty"
//or use .isLength({min: 5}) which means
//minimum value of 5 characters are only allowed
[
check('Username', 'Username is required').isLength({min: 5}),
check('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric(),
check('Password', 'Password is required').not().isEmpty(),
check('Email', 'Email does not appear to be valid').isEmail()
], (req, res) => {
// check the validation object for errors
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
let hashedPassword = Users.hashPassword(req.body.Password);
Users.findOne({ Username: req.body.Username }) // Search to see if a user with the requested username already exists
.then((user) => {
if (user) {
//If the user is found, send a response that it already exists
return res.status(400).send(req.body.Username + 'already exists');
} else {
Users
.create({
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthday: req.body.Birthday
})
.then((user) =>{res.status(201).json(user) })
.catch((error) => {
console.error(error);
res.status(500).send('Error: ' + error);
})
}
})
.catch((error) => {
console.error(error);
res.status(500).send('Error: ' + error);
});
});
// Update a user's info, by username
/* We’ll expect JSON in this format
{
Username: String,
(required)
Password: String,
(required)
Email: String,
(required)
Birthday: Date
}*/
app.put('/users/:Username',
// Validation logic here for request
//you can either use a chain of methods like .not().isEmpty()
//which means "opposite of isEmpty" in plain english "is not empty"
//or use .isLength({min: 5}) which means
//minimum value of 5 characters are only allowed
[
check('Username', 'Username is required').isLength({min: 5}),
check('Username', 'Username contains non alphanumeric characters - not allowed.').isAlphanumeric(),
check('Password', 'Password is required').not().isEmpty(),
check('Email', 'Email does not appear to be valid').isEmail()
], passport.authenticate('jwt',{session: false}), (req, res) => {
// check the validation object for errors
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
Users.findOneAndUpdate({ Username: req.params.Username },
{ $set:
{
Username: req.body.Username,
Password: req.body.Password,
Email: req.body.Email,
Birthday: req.body.Birthday
}
},
{ new: true }, // This line makes sure that the updated document is returned
(err, updatedUser) => {
if(err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
});
});
// Add a movie to a user's list of favorites
app.post('/users/:Username/movies/:MovieID', passport.authenticate('jwt',{session: false}), (req, res) => {
Users.findOneAndUpdate({ Username: req.params.Username }, {
$push: { FavoriteMovies: req.params.MovieID }
},
{ new: true }, // This line makes sure that the updated document is returned
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
});
});
// Delete a user by username
app.delete('/users/:Username', passport.authenticate('jwt',{session: false}), (req, res) => {
Users.findOneAndRemove({ Username: req.params.Username })
.then((user) => {
if (!user) {
res.status(400).send(req.params.Username + ' was not found');
} else {
res.status(200).send(req.params.Username + ' was deleted.');
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
});
// Delete movie from favorites
app.delete('/users/:Username/favorites/:MovieID', passport.authenticate("jwt", { session: false }), (req, res) => {
Users.findOneAndUpdate({ Username: req.params.Username },
{ $pull: { FavoriteMovies: req.params.MovieID } },
{ new: true },
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
}
);
});
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('An error has been detected')
});
// listen for requests
const port = process.env.PORT || 8080;
app.listen(port, '0.0.0.0',() => {
console.log('Listening on Port ' + port);
});