-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
82 lines (72 loc) · 2.49 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
const express = require("express");
const bodyParser = require("body-parser");
const ejs = require("ejs");
const _ = require("lodash");
const dotenv = require('dotenv');
const mongoose = require("mongoose");
dotenv.config();
const app = express();
app.set("view engine", "ejs");
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.static("public"));
// ---------------------- Mongoose DB connect ----------------------
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
// ---------------------- Mongoose DB schema ----------------------
const postScheme = new mongoose.Schema({ title: String, content: String });
const Post = mongoose.model("Post", postScheme);
const homeStartingContent = "Add '/compose' at the end of ☝🏻url to add a new post";
const aboutContent = "Hi! This Daily Journal was made by Mitali Laroia 🤓 ";
const contactContent = "Heya! Reach me at [email protected]";
// ---------------------- Home Route ----------------------
app.get("/", (req, res) => {
Post.find({}, (e, foundPosts) => {
res.render("home", { content: homeStartingContent, posts: foundPosts });
});
});
// ---------------------- About Route ----------------------
app.get("/about", (req, res) => {
res.render("about", { content: aboutContent });
});
// ---------------------- Contact Route ----------------------
app.get("/contact", (req, res) => {
res.render("contact", { content: contactContent });
});
// ---------------------- Compose Route ----------------------
app.get("/compose", (req, res) => {
res.render("compose");
});
// ---------------------- Compose Post Route ----------------------
app.post("/compose", (req, res) => {
const post = new Post({
title: req.body.postTitle,
content: req.body.postBody,
});
post.save((e) => {
if (!e) {
res.redirect("/");
}
});
});
app.get("/posts/:postName", (req, res) => {
const postName = _.lowerCase(req.params.postName);
Post.find({}, (e, foundPosts) => {
if (!e) {
for (let i = 0; i < foundPosts.length; i++) {
let storedTitle = _.lowerCase(foundPosts[i].title);
if (storedTitle === postName) {
res.render("post", { title: foundPosts[i].title, content: foundPosts[i].content });
break;
}
console.log("Post not found. Redirecting to Home Page");
res.redirect("/");
}
}
});
});
const port = process.env.PORT || 3000;
app.listen(port, function () {
console.log("Server started on port 3000");
});