-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
340 lines (319 loc) · 8.66 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
// Import modules
const express = require('express'),
morgan = require('morgan'),
fs = require('fs'),
path = require('path'),
res = require('express/lib/response'),
mongoose = require('mongoose'),
Models = require('./models.js'),
bodyParser = require('body-parser'),
cors = require('cors'),
{ check, validationResult } = require('express-validator');
// Create Express app
const app = express();
// Import User and Movie models
const Users = Models.User;
const Movies = Models.Movie;
// Create a write stream in append mode . . .
// 'log.txt' is created in root dir
const accessLogStream = fs.createWriteStream(path.join(__dirname, 'log.txt'), {
flags: 'a',
});
// CORS
// app.use(cors()); //cross origin resource sharing
let allowedOrigins = [
'http://localhost:8080',
'http://localhost:1234',
'http://localhost:3000',
'http://127.0.0.1:1234',
'http://127.0.0.1:8080',
'http://127.0.0.1:3000',
'https://jackie-chan-movie-api.herokuapp.com/',
'https://jackie-chan-movie-db.netlify.app',
];
app.use(
cors({
origin: (origin, callback) => {
if (!origin) return callback(null, true);
if (allowedOrigins.indexOf(origin) === -1) {
let message =
'The CORS policy for this application doesn’t allow access from origin ' +
origin;
return callback(new Error(message), false);
}
return callback(null, true);
},
})
);
// Middleware
app.use(morgan('common')); //log stuff to console
app.use(morgan('combined', { stream: accessLogStream })); //log stuff to log.txt
app.use(express.static('public')); //serve static files
app.use(bodyParser.json()); //parse headerbody
app.use(bodyParser.urlencoded({ extended: true })); //parse headerbody
// Import required for auth
let auth = require('./auth')(app);
const passport = require('passport');
require('./passport');
// Connect to MongoDB
mongoose
.connect(process.env.CONNECTION_URI, {
// .connect('mongodb://localhost:27017/jackieMovieAPI', {
useNewUrlParser: true,
useUnifiedTopology: true,
})
.then(() => {
console.log('CONNECTION TO MONGO OPEN!!!');
})
.catch((err) => {
console.log('OH NO! ERROR TRYING TO CONNECT TO MONGO!!!');
console.log(err);
});
// BEGINNING of - Routing endpoints
// Create new user
app.post(
'/users/new',
[
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) => {
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 })
.then((user) => {
if (user) {
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);
});
}
);
// 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);
});
}
);
// Update a user's info, by username
app.put(
'/users/:Username/edit',
[
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) => {
let errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(422).json({ errors: errors.array() });
}
let hashedPassword = Users.hashPassword(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 },
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
}
);
}
);
// Delete user
app.delete(
'/users/:Username/remove',
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);
});
}
);
// Add fav movie
app.post(
'/users/:Username/favorites/add/:MovieID',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Users.findOneAndUpdate(
{ Username: req.params.Username },
{
$push: { FavoriteMovies: req.params.MovieID },
},
{ new: true },
(err, updatedUser) => {
if (err) {
console.error(err);
res.status(500).send('Error: ' + err);
} else {
res.json(updatedUser);
}
}
);
}
);
// Delete fav movie
app.delete(
'/users/:Username/favorites/remove/: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);
}
}
);
}
);
// Get all movies
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);
});
}
);
// Get a movie, by title
app.get(
'/movies/:Title',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ Title: req.params.Title })
.then((movie) => {
res.json(movie);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Get info about a genre
app.get(
'/movies/genre/:Name',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ 'Genre.Type': req.params.Type })
.then((movie) => {
res.json(movie.Genre.Description);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
);
// Get info about a director
app.get(
'/movies/directors/:Name',
passport.authenticate('jwt', { session: false }),
(req, res) => {
Movies.findOne({ 'Director.Name': req.params.Name })
.then((movie) => {
res.json(movie.Director.Bio);
})
.catch((err) => {
console.error(err);
res.status(500).send('Error: ' + err);
});
}
); //END of - Routing endpoints
// Error handling
app.use((err, req, res, next) => {
console.error(err.stack);
res.status(500).send('Something went wrong!!!');
});
const port = process.env.PORT || 8080;
app.listen(port, '0.0.0.0', () => {
console.log('The Jackie Chan Movie app is listening on port ' + port);
});