-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
163 lines (146 loc) · 4.83 KB
/
app.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
const express = require('express');
const mustacheExpress = require('mustache-express');
const bodyParser = require('body-parser');
const cookieParser = require('cookie-parser');
const cookieSession = require('cookie-session');
const mongoose = require('mongoose');
const Movie = require('./models/Movie');
const app = express();
app.engine('mst', mustacheExpress());
app.set('view engine', 'mst');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());
app.use(cookieSession({ secret: "qwerty" }));
mongoose.Promise = global.Promise;
mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost/movies');
// Cookie based auth on all requests.
app.use((req, res, next) => {
if (req.cookies['allowed'] === 'yes') {
next();
} else {
res.sendStatus(401);
}
});
app.get('/', (req, res) => {
const ctx = { 'title': 'Home' };
ctx.formSuccessMsg = req.session.formSuccessMsg;
req.session = null;
Movie.find({}, (err, movies) => {
ctx.movies = movies;
res.render('list', ctx);
});
});
app.get('/view/:movieId', (req, res) => {
Movie.findById(req.params['movieId'], (err, movie) => {
if (err) {
res.sendStatus(404);
} else {
const ctx = {
title: movie.title,
movie: movie
};
res.render('view', ctx);
}
});
});
app.route('/new')
.get((req, res) => {
const ctx = createContextForFormGet(req, req.session.movie || null, 'Create Movie',
'Create Movie', 'Your Movie was created successfully!');
req.session = null;
res.render('new', ctx);
})
.post((req, res) => {
const newMovie = new Movie({
title: req.body['title'],
yearReleased: req.body['yearReleased']
});
saveMovieThenRedirect(req, res, newMovie);
});
app.route('/edit/:movieId')
.get((req, res) => {
Movie.findById(req.params['movieId'], (err, movie) => {
if (err) {
res.sendStatus(404);
} else {
const ctx = createContextForFormGet(req, req.session.movie || movie, 'Edit Movie',
'Edit Movie', 'Your Movie was edited successfully!');
req.session = null;
res.render('edit', ctx);
}
});
})
.post((req, res) => {
Movie.findById(req.params['movieId'])
.then(originalMovie => {
originalMovie.title = req.body['title'];
originalMovie.yearReleased = req.body['yearReleased'];
saveMovieThenRedirect(req, res, originalMovie);
}, err => {
res.sendStatus(404);
});
});
// HTML forms only support GET and POST, so re-write request method to DELETE.
app.post('/delete/:movieId', (req, res, next) => {
req.method = 'DELETE';
next();
});
app.route('/delete/:movieId')
.get((req, res) => {
Movie.findById(req.params['movieId'], (err, movie) => {
if (err) {
res.sendStatus(404);
} else {
const ctx = createContextForFormGet(req, movie, 'Delete Movie',
'', 'Your Movie was deleted successfully!');
req.session = null;
res.render('delete', ctx);
}
});
})
.delete((req, res) => {
Movie.findById(req.params['movieId'])
.then(movie => {
movie.remove((err, movie) => {
if (err) {
res.sendStatus(500);
} else {
req.session.formSuccessMsg = 'Movie deletion successful!';
res.redirect('/');
}
});
}, err => {
res.sendStatus(404);
});
});
function createContextForFormGet(req, movie, title, submitBtnText, formSuccessMsg) {
const ctx = {
title: title,
movie: movie,
submitBtnText: submitBtnText
};
if (req.session.afterRedirect) {
if (req.session.formSuccessful) {
ctx.formSuccessMsg = formSuccessMsg;
} else if (req.session.validationErrors) {
ctx.validationErrors = req.session.validationErrors;
}
}
return ctx;
}
function saveMovieThenRedirect(req, res, originalMovie) {
originalMovie.save((err, updatedMovie) => {
if (err) {
req.session.movie = originalMovie;
req.session.validationErrors = Object.keys(err.errors).map(k => err.errors[k]);
} else {
req.session.movie = updatedMovie;
req.session.formSuccessful = true;
}
req.session.afterRedirect = true;
res.redirect(req.originalUrl);
});
}
app.listen(process.env.PORT || 3000, () => {
console.log('Listening...');
});