-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
365 lines (348 loc) · 10.1 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
const express = require('express'),
bodyParser = require('body-parser'),
mongoose = require('mongoose'),
Models = require('./models.js'),
morgan = require('morgan');
const passport = require('passport');
require('./passport');
const app = express();
const Movies = Models.Movie;
const Users = Models.User;
//Local connection
// mongoose.connect('mongodb://localhost:27017/victorvilleDB', {
// useNewUrlParser: true,
// useUnifiedTopology: true,
// });
// Connection to Remote DB on MongoDBAtlas
mongoose.connect(process.env.CONNECTION_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
mongoose.set('useFindAndModify', false);
const { check, validationResult } = require('express-validator');
const cors = require('cors');
app.use(cors());
/*
CORS - Allowed origins/domains
*/
var allowedOrigins = [
'http://localhost:8080',
'http://localhost:1234',
'https://vfa.herokuapp.com/',
];
app.use(
cors({
origin: function (origin, callback) {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
// If a specific origin isn’t found on the list of allowed origins
var message =
'The CORS policy for this application doesn’t allow access from origin ' +
origin;
return callback(new Error(message), false);
}
return callback(null, true);
},
})
);
// Midddleware
app.use(morgan('common'));
app.use(bodyParser.json());
var auth = require('./auth')(app);
app.use(function (err, req, res, next) {
console.error(err.stack);
res.status(500).send('Something broke!');
});
/*
API methods
*/
// Hit main page
app.get('/', function (req, res) {
res.status(200).send('Welcome to the Victorville Film Archives!');
});
// Get all movies in db
app.get('/movies', passport.authenticate('jwt', { session: false }), function (
req,
res
) {
Movies.find().then((movies) => res.status(200).json(movies));
});
// Get Movies by Title
app.get(
'/movies/:title',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Movies.findOne({ Title: req.params.title }).then(function (title) {
if (title) {
res.status(200).json(title);
} else {
const message = 'Title not found in db';
res.status(404).send(message);
}
});
}
);
// Get Genre by Name
app.get(
'/movies/genre/:name',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Movies.findOne({ 'Genre.Name': req.params.name }).then(function (genre) {
if (genre) {
res.status(200).json(genre.Genre);
} else {
const message = 'No Genre matching that name in the db';
res.status(404).send(message);
}
});
}
);
// Get Director by Name
app.get(
'/movies/directors/:name',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Movies.findOne({ 'Director.Name': req.params.name }).then(function (
director
) {
if (director) {
res.status(200).json(director.Director);
} else {
const message = 'No Director matching that name in the db';
res.status(404).send(message);
}
});
}
);
// Get User Account by username
app.get(
'/users/:name',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Users.findOne({ Username: req.params.name }).then(function (user) {
if (user) {
res.status(200).json(user);
} else {
const message = 'No Account matching that name in the db';
res.status(404).send(message);
}
});
}
);
// Create User Account
app.post(
'/users',
// Validation logic
[
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(),
],
function (req, res) {
// check the validation object for errors
var errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
var hashedPassword = Users.hashPassword(req.body.Password);
// db check if user already exists
Users.findOne({ Email: req.body.Email })
.then(function (user) {
if (user) {
const message =
'There is already an account associated with this email address';
res.status(400).send(message);
} else {
Users.create({
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthday: req.body.Birthday,
})
.then(function (user) {
res.status(201).json(user);
})
.catch(function (error) {
console.error(error);
res.status(500).send('Error: ' + error);
});
}
})
.catch(function (error) {
console.error(error);
res.status(500).send('Error: ' + error);
});
}
);
// Deregister User Account
app.delete(
'/users/:userId',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Users.findOneAndRemove({ _id: req.params.userId })
.then(function () {
const message =
'User account with userId ' +
req.params.userId +
' was successfully deleted';
return res.status(200).send(message);
})
.catch(function (err) {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Update User Account
app.put(
'/users/update/:userId',
passport.authenticate('jwt', { session: false }),
// Validation logic
[
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(),
],
function (req, res) {
// check the validation object for errors
var errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
var hashedPassword = Users.hashPassword(req.body.Password);
// Check if id matches a user
Users.findOne({ _id: req.params.userId })
.then(function (user) {
if (user) {
Users.findOneAndUpdate(
{ _id: req.params.userId },
{
$set: {
// --Remind for v2--
// Add logic to only update what is in request body maybe can do that in UI i/e include any key/value that is not given
Username: req.body.Username,
Password: hashedPassword,
Email: req.body.Email,
Birthday: req.body.Birthday,
},
},
{ new: true }
)
.then(function (user) {
res.status(200).json(user);
})
.catch(function (err) {
console.error(err);
res.status(500).send('Error: ' + err);
});
} else {
const message = 'No user matching that id in the db';
res.status(404).send(message);
}
})
.catch(function (err) {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Add Movie to Favourites List by Movie ID
app.post(
'/users/:userId/favourites/:movieId/',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Users.find({ _id: req.params.userId }, function (err, user) {
if (user) {
// check duplicate
let list = user[0].FavouriteMovies;
if (list.includes(req.params.movieId)) {
return res.status(400).send('Already movie in your favourites list');
} else {
// add to favourites
Users.findOneAndUpdate(
{ _id: req.params.userId },
{
$push: { FavouriteMovies: req.params.movieId },
},
{ new: true }
)
.then(function (updatedUser) {
res
.status(200)
.json(
'Updated Favourites list: [' +
updatedUser.FavouriteMovies +
']'
);
})
.catch(function (err) {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
} else {
console.error(err);
res.status(500).send('Error: ' + err);
}
});
}
);
// Remove Movie from Favourites List by Move ID
app.delete(
'/users/:userId/favourites/:movieId/',
passport.authenticate('jwt', { session: false }),
function (req, res) {
Users.find({ _id: req.params.userId }, function (err, user) {
if (user) {
// check duplicate
let list = user[0].FavouriteMovies;
console.log(user[0]);
if (!list.includes(req.params.movieId)) {
return res
.status(400)
.send('No movie matching that ID in the Favourites list');
} else {
// add to favourites
Users.findOneAndUpdate(
{ _id: req.params.userId },
{
$pull: { FavouriteMovies: req.params.movieId },
},
{ new: true }
)
.then(function (updatedUser) {
res
.status(200)
.json(
'Movie with id ' +
req.params.movieId +
' was succesfully deleted. Updated Favourites list: [' +
updatedUser.FavouriteMovies +
']'
);
})
.catch(function (err) {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
} else {
console.error(err);
res.status(500).send('Error: ' + err);
}
});
}
);
// listen for requests
var port = process.env.PORT || 3000;
app.listen(port, '0.0.0.0', function () {
console.log(`Listening on Port ${port}`);
});