-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
78 lines (62 loc) · 1.78 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
const express = require("express")
const _ = require("lodash")
const mongoose = require("mongoose")
const { Post, defaultItems } = require("./Model")
require("dotenv").config({ path: "vars/.env" })
const MUSER = process.env.USER
const MPASS = process.env.PASS
const app = express()
const port = process.env.PORT || 3000
const uri =
"mongodb+srv://" +
MUSER +
":" +
MPASS +
"@abdallah.qb7z6xt.mongodb.net/blogDB?retryWrites=true&w=majority"
app.set("view engine", "ejs")
app.use(express.urlencoded({ extended: true }))
app.use(express.static("public"))
var posts = []
main().catch((err) => console.log(err))
async function main() {
await mongoose.connect(uri)
}
app.get("/", async (req, res) => {
const foundPosts = await Post.find({})
if (!(await Post.exists())) {
await Post.insertMany(defaultItems[1])
res.redirect("/")
} else {
res.render("home", {
startingContent: defaultItems[0],
posts: foundPosts,
})
}
})
app.get("/about", (req, res) => {
res.render("about", { aboutContent: defaultItems[2] })
})
app.get("/contact", (req, res) => {
res.render("contact", { contactContent: defaultItems[3] })
})
app.get("/compose", (req, res) => {
res.render("compose")
})
app.get("/posts/:postId", async (req, res) => {
const requestedPostId = req.params.postId
const post = await Post.findOne({ _id: requestedPostId })
res.render("post", { title: post.title, content: post.content })
})
app.post("/compose", async (req, res) => {
const post = new Post({
title: req.body.postTitle,
content: req.body.postBody,
url: "/posts/" + req.body.postTitle.replace(/\s+/g, "-").toLowerCase(),
})
await post.save()
res.redirect("/")
})
app.listen(port, function (err) {
if (err) console.log(err)
console.log(`Listening on PORT ${port}.`)
})