forked from ALPHAVIO/WordNook
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
338 lines (307 loc) · 9.48 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
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
//jshint esversion:6
//Acquiring Dependencies-
const express = require("express");
const bodyParser = require("body-parser");
const cookieParser = require("cookie-parser");
const ejs = require("ejs");
const mongoose = require('mongoose');
const _ = require("lodash");
const PORT = process.env.PORT || 3000;
const auth = require('./middlewares/auth');
const router = require("./routes/user.router");
const { post } = require("./routes/user.router");
const Blog = require('./models/Blog.model')
const connectDB = require('./config/db');
//Setting up the app and the ejs view engine-
const app = express();
app.set('view engine', 'ejs');
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
app.use(express.json());
app.use(cookieParser());
//When in development mode then only require the dotenv module
if (process.env.NODE_ENV !== 'production') {
const dotenv = require('dotenv');
dotenv.config({ path: './.env' });
}
//Connecting to Mongo Database using ODM Mongoose-
connectDB();
//Setting up schema for the collection-
const blogSchema = {
blogTitle: String,
blogContent: String,
comments: Array,
timestamps: {
type: Date,
default: Date.now
},
likes:[
{
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
],
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User"
}
}
//Making a MongoDB model for the schema-
const Blog = new mongoose.model("Blog", blogSchema);
mongoose.set('useCreateIndex', true);
// Router for user login and sign in
app.use(require("./routes/user.router"));
//Get request for home route-
app.get(["/", "/page/:page", "/page/:perPage", "/page/:page/:perPage"], auth, function(req, res){
var perPage = parseInt(req.params.perPage) || 5;
if(req.query.perPage>0)
perPage = parseInt(req.query.perPage);
const currentPage = req.params.page || 1;
const order = req.query.order || "new one first";
Blog
.find({})
.sort({'timestamps': (order === "new one first")?'desc':'asc'})
.skip((perPage * currentPage) - perPage)
.limit(perPage)
.exec(function(err, foundBlogs) {
Blog.count().exec(function(err, count) {
if(err)
console.log(err);
else {
res.render("home", {
homeStartingContent: homeStartingContent,
posts: foundBlogs,
current: currentPage,
pages: Math.ceil(count/perPage),
search: "",
perPage: perPage,
order: order,
isAuthenticated: req.user? true: false,
currentUser: req.user
});
}
})
});
});
//Get request for about page-
app.get("/about", auth, function(req, res){
res.render("about", {
aboutContent: aboutContent,
isAuthenticated: req.user? true : false
});
});
//Get request for contact page-
app.get("/contact", auth, function(req, res){
res.render("contact", {
contactContent: contactContent,
isAuthenticated: req.user? true : false
});
});
//Get request for compose blog page-
app.get("/compose", auth, function(req, res){
const user = req.user;
if(!user){
return res.status(401).redirect("/log-in");
}
res.render("compose", {
isAuthenticated: true
});
});
//Post request to save the new blogs to the DB
app.post("/compose", auth, function(req, res){
const user = req.user;
if(!user){
return res.status(401).redirect("/log-in");
}
const postTitle = req.body.postTitle;
const postContent = req.body.postBody;
const blog = new Blog({
blogTitle: postTitle,
blogContent: postContent,
comments: [],
likes: [],
author: user._id
})
console.log(blog);
blog.save();
res.redirect("/");
});
//Get request for posts page-
app.get(["/posts/:postName", "/page/posts/:postName", "/page/:page/posts/:postName", "/search/:query/posts/:postName", "/search/:query/:page/posts/:postName"], auth, function(req, res){
const user = req.user;
let isAuthor = false;
const requestedTitle = _.lowerCase(req.params.postName);
Blog.find({}, function(err, posts){
if(!err){
posts.forEach(function(post){
const storedTitle = _.lowerCase(post.blogTitle);
if(storedTitle === requestedTitle){
// Check if the user and author of this post are same
if(user && JSON.stringify(user._id) === JSON.stringify(post.author)){
isAuthor = true;
}
//Sort the comments to show the recent one
post.comments = post.comments.sort((a,b) => ((a.timestamps > b.timestamps) ? -1 : ((a.timestamps < b.timestamps) ? 1 : 0)));
res.render("post", {
title: post.blogTitle,
content: post.blogContent,
id:post._id,
comments: post.comments,
isAuthor,
isAuthenticated: user? true: false,
currentUser: user,
likes: post.likes
});
}
});
}
else{
console.log(err);
}
});
});
//Post request to create a comment
app.post("/posts/:postName/comment",auth, async function(req, res) {
const loggedUser=req.user;
const {content} = req.body;
//check if the user is authenticated
if(!loggedUser){
return res.status(401).redirect(req.baseUrl+"/sign-up");
}
//Server side form validation
else if(content===""){
res.redirect(`/posts/${req.params.postName}`);
}
else {
const doc = await Blog.findOne({blogTitle: req.params.postName});
doc.comments.push({'name': loggedUser.name,
'content': content,
'timestamps': Math.floor(Date.now() / 1000)});
await Blog.updateOne({blogTitle: req.params.postName}, {comments: doc.comments}, function(err, doc) {
if(err)
console.log(err);
})
res.redirect(`/posts/${req.params.postName}`);
}
});
// Delete comment Route
app.post("/posts/:postName/comments/:commentNum",auth,async function(req,res){
const isUser=req.user?true:false;
const requestedPost = req.params.postName;
const commentNum=req.params.commentNum;
if(!isUser){ // checking if user is authenticated
return res.status(401).redirect(req.baseUrl+"/sign-up");
}else{
const foundPost=await Blog.findOne({blogTitle: requestedPost});
foundPost.comments = foundPost.comments.sort((a,b) => ((a.timestamps > b.timestamps) ? -1 : ((a.timestamps < b.timestamps) ? 1 : 0)));
foundPost.comments.splice(commentNum,1);
await Blog.updateOne({blogTitle: requestedPost}, {comments: foundPost.comments}, function(err, foundPost) {
if(err)
console.log(err);
})
res.redirect(`/posts/${requestedPost}`);
}
})
//router for post and search related urls
app.use(require("./routes/post.router"));
// router for the requests from home page
app.use(require("./routes/index.router"));
Blog.find({blogTitle: { "$regex": query, "$options": "i" }})
.skip((perPage * currentPage) - perPage)
.sort({'timestamps': 'desc'})
.limit(perPage)
.exec( function(err, posts) {
Blog.countDocuments({blogTitle: { "$regex": query, "$options": "i" }}, function(err, count) {
res.render("home", {
homeStartingContent: homeStartingContent,
posts: posts,
current: currentPage,
pages: Math.ceil(count/perPage),
search: query,
perPage: perPage,
order: 'new one first',
isAuthenticated: req.user? true : false,
currentUser: req.user
});
})
})
// GET request for search to support pagination
app.get(["/search/:query/:page", "/search/:query", "/search/:query/:page/:perPage", "/search/:query"], auth, function(req, res){
const query = req.params.query;
var perPage = parseInt(req.params.perPage) || 5;
if(req.query.perPage>0)
perPage = parseInt(req.query.perPage);
const order = req.query.order || "new one first";
const currentPage = req.params.page || 1;
Blog.find({blogTitle: { "$regex": query, "$options": "i" }})
.sort({'timestamps': (order === "new one first")?'desc':'asc'})
.skip((perPage * currentPage) - perPage)
.limit(perPage)
.exec( function(err, posts) {
Blog.countDocuments({blogTitle: { "$regex": query, "$options": "i" }}, function(err, count) {
res.render("home", {
homeStartingContent: homeStartingContent,
posts: posts,
current: currentPage,
pages: Math.ceil(count/perPage),
search: query,
perPage: perPage,
order: order,
isAuthenticated: req.user? true: false,
currentUser: req.user
});
})
})
})
//delete post route
app.post('/posts/:postName', auth, (req, res, next) => {
const user = req.user;
if(!user) {
return res.status(401).redirect("/log-in");
}
const requestedTitle = req.params.postName;
console.log(requestedTitle)
Blog.deleteOne({blogTitle: requestedTitle, author: user._id}).then(
() => {
res.redirect("/");
}
).catch(
(error) => {
res.status(400).json({
error: error
});
}
);
});
// Put route for likes
app.put('/like', auth, (req,res)=>{
Blog.findByIdAndUpdate(req.body.postId,{
$push: {likes:req.user._id}
},{
}).exec((err,result)=> {
if(err){
return res.status(422).json({error:err});
}
else{
res.json(result);
}
})
})
// Put route for unlike
app.put('/unlike', auth, (req,res)=>{
Blog.findByIdAndUpdate(req.body.postId,{
$pull: {likes:req.user._id}
},{
}).exec((err,result)=> {
if(err){
return res.status(422).json({error:err});
}
else{
res.json(result);
}
})
})
//Launching the server on port 3000 in development mode-
app.listen(PORT, function () {
console.log("Server started on port 3000");
});