-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
113 lines (99 loc) · 2.53 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
let express = require("express")
let methodOverride = require("method-override")
let expressSanitizer = require("express-sanitizer")
let bodyParser = require("body-parser")
let mongoose = require("mongoose")
app = express()
// APP CONFIG
mongoose.connect("mongodb://localhost:27017/blogul",
{
useNewUrlParser: true,
useUnifiedTopology: true
}
)
app.set("view engine", "ejs")
app.use(express.static(__dirname + '/public'))
app.use(bodyParser.urlencoded({extended: true}))
app.use(expressSanitizer())
app.use(methodOverride("_method"))
//MONGOOSE/MODEL CONFIG
let blogulSchema = new mongoose.Schema({
title: String,
image: String,
body: String,
created: {type: Date, default: Date.now}
})
let Blogul = mongoose.model("Blogul", blogulSchema)
// RESTFUL ROUTES
// INDEX ROUTE
app.get("/", function(req, res){
res.redirect("/blogul")
})
app.get("/blogul", function(req, res){
Blogul.find({}, function(err, bloguls){
if(err){
console.log(err)
} else{
res.render("index", {bloguls: bloguls})
}
})
})
//NEW ROUTE
app.get("/blogul/new", function(req, res){
res.render("new")
})
//CREATE ROUTE
app.post("/blogul", function(req, res){
req.body.blogul.body = req.sanitize(req.body.blogul.body)
Blogul.create(req.body.blogul, function(err, newblogul){
if(err){
res.render('new')
} else{
res.redirect("/blogul")
}
})
})
//SHOW ROUTE
app.get("/blogul/:id", function(req, res){
Blogul.findById(req.params.id, function(err, foundblogul){
if(err){
console.log(err)
} else{
res.render("show", {foundblogul: foundblogul})
}
})
})
//EDIT ROUTE
app.get("/blogul/:id/edit", function(req, res){
Blogul.findById(req.params.id, function(err, foundblogul){
if(err){
res.render("/blogul")
} else{
res.render("edit", {foundblogul: foundblogul})
}
})
})
//UPDATE ROUTE
app.put("/blogul/:id", function(req, res){
req.body.blogul.body = req.sanitize(req.body.blogul.body)
Blogul.findByIdAndUpdate(req.params.id, req.body.blogul, function(err, updatedblogul){
if(err){
res.redirect("/blogul")
} else{
res.redirect("/blogul/" + req.params.id)
}
})
})
//DELETE ROUTE
app.delete("/blogul/:id", function(req, res){
Blogul.findByIdAndRemove(req.params.id, function(err){
if(err){
console.log(err)
} else{
res.redirect("/blogul")
}
})
})
app.listen(process.env.PORT || 3000, function(){
console.log("Blogul server started at PORT: 3000")
})