-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
495 lines (473 loc) · 13.7 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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
// Imports & initializations
const port = process.env.PORT || 8080;
const express = require('express'),
morgan = require('morgan'),
// uuid = require('uuid'),
bodyParser = require('body-parser'),
passport = require('passport'),
cors = require('cors');
/**
* Express Application
* @constant
*/
const app = express();
const { check, validationResult } = require('express-validator');
const mongoose = require('mongoose');
const Models = require('./models.js');
const Movies = Models.Movie;
const Users = Models.User;
// LOCAL DATABASE
// mongoose.connect('mongodb://localhost:27017/myFlixDB', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// });
// REMOTE DATABASE - MongoDB Atlas
mongoose.connect(process.env.CONNECTION_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// Hard-coded "in memory" array with 10 movies
let topMovies = [
{
title: 'The Best of Enemies',
description:
'Inspired by true events. Civil rights activist Ann Atwater faces off against C.P. Ellis, Exalted Cyclops of the Ku Klux Klan, in 1971 Durham, North Carolina over the issue of school integration.',
genre: 'Drama',
imageURL: '',
Released: 2019,
Rating: 7.4,
director: 'Robin Bissel',
},
{
title: 'The Name of the Rose',
description:
'Historical mystery film directed by Jean-Jacques Annaud, based on the 1980 novel of the same name by Umberto Eco. An intellectually non-conformist friar investigates a series of mysterious deaths in an isolated abbey.',
genre: 'Mystery',
imageURL: '',
released: 1986,
rating: 7.7,
director: 'Jean-Jacques Annaud',
},
{
title: 'The Lord of The Rings - The Fellowship of the Ring',
description:
"The Fellowship of the Ring is a 2001 epic fantasy adventure film directed by Peter Jackson, based on the first volume of J. R. R. Tolkien's The Lord of the Rings. The film is the first instalment in The Lord of the Rings trilogy",
genre: 'Adventure',
imageURL: '',
released: 2001,
rating: 8.8,
director: 'Peter Jackson',
},
{
title: 'Dune',
description:
"Epic science fiction film. A noble family becomes embroiled in a war for control over the galaxy's most valuable asset while its heir becomes troubled by visions of a dark future.",
genre: 'Adventure',
imageURL: '',
released: 2021,
rating: 8.1,
director: 'Denis Villeneuve',
},
{
title: 'Arrival',
description:
'A linguist works with the military to communicate with alien lifeforms after twelve mysterious spacecraft appear around the world.',
genre: 'Sci-Fi',
imageURL: '',
released: 2016,
rating: 7.9,
director: 'Denis Villeneuve',
},
{
title: 'Edge of Tomorrow',
description:
'A soldier fighting aliens gets to relive the same day over and over again, the day restarting every time he dies.',
genre: 'Sci-Fi',
imageURL: '',
released: 2014,
rating: 7.9,
director: 'Doug Liman',
},
{
title: '12 Years a Slave',
description:
'Biographical drama based on the 1853 slave memoir "Twelve Years a Slave" by David Wilson, about a New York State-born free African-American man named Solomon Northup, who was kidnapped in Washington, D.C.',
genre: 'Drama',
imageURL: '',
released: 2013,
rating: 8.1,
director: 'Steve McQueen',
},
{
title: '300',
description:
'Epic historical action film in which King Leonidas of Sparta and a force of 300 men fight the Persians at Thermopylae in 480 B.C.',
genre: 'Action',
imageURL: '',
released: 2006,
rating: 7.6,
director: 'Zack Snyder',
},
{
title: 'Apocalypto',
description:
'As the Mayan kingdom faces its decline, a young man is taken on a perilous journey to a world ruled by fear and oppression.',
genre: 'Action',
genre: '',
released: 2006,
rating: 7.8,
director: 'Mel Gibson',
},
{
title: 'Bohemian Rapsody',
description:
'The story of the legendary British rock band Queen and lead singer Freddie Mercury, leading up to their famous performance at Live Aid (1985).',
genre: 'Drama',
imageURL: '',
released: 2018,
rating: 7.9,
director: 'Bryan Singer',
},
];
// MIDDLEWARE--------------------------------------------------------------
app.use(cors());
app.use(morgan('common'));
app.use(express.static('public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// ROUTING ENDPOINTS-------------------------------------------------------
// We call the exported function in auth.js, passing it our app to set the 'POST /login' Endpoint
let auth = require('./auth')(app);
// Root directory of API
// returns a Welcome text
app.get('/', (req, res) => {
res.send('Welcome to myFlix API!');
});
// Retrieve List of movies
app.get(
'/movies',
passport.authenticate('jwt', { session: false }), //Only with JWTStrategy
(req, res) => {
Movies.find()
.then((movies) => {
res.status(201).json(movies);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Retrieve movie info by movieID
app.get(
'/movies/:movieID',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ _id: req.params.movieID })
.then((movie) => {
console.log(req.params.movieID);
if (movie) {
res.status(201).json(movie);
} else {
res
.status(404)
.send(`Movie with ID: "${req.params.movieID}" was not found...`);
}
})
.catch((err) => {
console.log(err);
res.status(500).send('Error: ' + error);
});
}
);
// Retrieve Genre info by name
app.get(
'/genres/:name',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ 'genre.name': req.params.name })
.then((movie) => {
if (!movie) {
res
.status(404)
.send(
`We currently don't have any movie of "${req.params.name}" genre.`
);
} else {
res.status(200).json(movie.genre);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Retrieve Director info by name
app.get(
'/directors/:name',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ 'director.name': req.params.name })
.then((movie) => {
if (!movie) {
res
.status(404)
.send(
`We currently don't have any movie directed by "${req.params.name}".`
);
} else {
res.status(200).json(movie.director);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Retrieve user by username
app.get(
'/users/:username',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Users.findOne({ username: req.params.username })
.then((user) => {
if (!user) {
res
.status(404)
.send(
`We don't have registered a user with username: "${req.params.username}".`
);
} else {
res.status(200).json(user);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Register a new user
app.post(
'/users',
// passport.authenticate('jwt', { session: false }),
[
check(
'username',
'Username is required and must have at least 5 characters.'
).isLength({ min: 5 }),
check(
'username',
'Username can only contain alphanumeric characters. Other symbols are not allowed.'
).isAlphanumeric(),
check(
'password',
'Password is required and must have at least 6 characters'
).isLength({ min: 6 }),
check('email', 'Email does not appear to be valid').isEmail(),
check(
'birthday',
'Birthday is required and must be a valid date.'
).isDate(),
],
(req, res) => {
// check the validation object from express-validator for errors
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
let hashedPassword = Users.hashSync(req.body.password);
Users.findOne({ username: req.body.username })
.then((user) => {
if (user) {
return res
.status(400)
.send(
`A user with the username: "${req.body.username}", already exists!`
);
} else {
Users.create({
username: req.body.username,
password: hashedPassword,
email: req.body.email,
birthday: new Date(req.body.birthday),
})
.then((user) => {
res.status(201).json(user);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Delete user
app.delete(
'/users/:username',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Users.findOneAndDelete({ username: req.params.username })
.then((user) => {
if (!user) {
res
.status(400)
.send(`The username: "${req.params.username}" was not found!`);
} else {
res
.status(200)
.send(
`The user with username: "${req.params.email}" was succesfully de-registered.`
);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Update info from a user
app.put(
'/users/:username',
[
check(
'username',
'Username is required and must have at least 5 characters.'
).isLength({ min: 5 }),
check(
'username',
'Username can only contain alphanumeric characters. Other symbols are not allowed.'
).isAlphanumeric(),
check(
'password',
'Password is required and must have at least 6 characters'
).isLength({ min: 6 }),
check('email', 'Email does not appear to be valid').isEmail(),
check(
'birthday',
'Birthday is required and must be a valid date.'
).isDate(),
],
passport.authenticate('jwt', { session: false }),
(req, res) => {
// check the validation object from express-validator for errors
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
let hashedPassword = Users.hashSync(req.body.password);
Users.findOneAndUpdate(
{ username: req.params.username },
{
$set: {
username: req.body.username,
password: hashedPassword,
email: req.body.email,
birthday: req.body.birthday,
},
},
{ new: true }
)
.then((updatedUser) => {
if (!updatedUser) {
res
.status(400)
.send(
`There's no registered user by the username "${req.params.username}".`
);
} else {
res.json(updatedUser);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Add movie to a user's favorites list
app.post(
'/users/:username/favorites/:movieID',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ _id: req.params.movieID })
.then((movie) => {
if (!movie) {
res
.status(404)
.send(
`The movie with the ID "${req.params.movieID}" is not registered in the database.`
);
} else {
Users.findOneAndUpdate(
{ username: req.params.username },
{ $addToSet: { favoriteMovies: req.params.movieID } },
{ new: true, fields: { username: 1, favoriteMovies: 1 } }
)
.then((user) => {
if (!user) {
res
.status(404)
.send(
`The user with username "${req.params.username}" is not registered in the database.`
);
} else {
res.status(200).json(user);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Delete movie from a user's favorites list
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, fields: { username: 1, favoriteMovies: 1 } }
)
.then((user) => {
if (!user) {
res
.status(404)
.send(
`The user with username "${req.params.username}" is not registered in the database.`
);
} else {
res.status(200).json(user);
}
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// ERROR HANDLING-----------------------------------------------------------
app.use((err, req, res, next) => {
console.log(err.stack);
res.status(500).send('Someting went wrong!');
});
// listen for requests------------------------------------------------------
app.listen(port, '0.0.0.0', () => {
console.log('Listening on port ' + port);
});