-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
111 lines (76 loc) · 2.41 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
const { urlencoded } = require("express");
const express = require("express");
const app = express();
const fs = require("fs");
app.use(express.urlencoded({extended: false}))
app.set("view engine", "pug");
app.use("/static", express.static("public"));
app.get("/", (req, res) => {
res.render("home");
});
app.get("/create", (req, res) => {
res.render("create")
})
app.post("/create", (req, postRes) => {
const title = req.body.title;
const blogBody = req.body.blogBody;
if (title.trim() === "" && blogBody.trim() === "") {
postRes.render("create", {error: true})
} else {
fs.readFile("./data/blogs.json", (err, data) => {
if (err) throw err;
const blogsData = JSON.parse(data);
blogsData.push({
id: id(),
title: title,
blogBody: blogBody
})
fs.writeFile("./data/blogs.json", JSON.stringify(blogsData), (err) => {
if (err) throw err
postRes.render("create", {success: true})
})
})
}
})
app.get("/blogs", (req, res) => {
fs.readFile("./data/blogs.json", (err, data) => {
if (err) throw err
const blogs = JSON.parse(data)
res.render("blogs", {blogs: blogs})
})
})
app.get("/blogs/:id", (req, res) => {
const id = req.params.id;
fs.readFile("./data/blogs.json", (err, data) => {
if (err) throw err
const blogs = JSON.parse(data)
const blog = blogs.filter(blog => blog.id == id)[0]
res.render("detail", {blog: blog} )
})
})
app.get("/api/v1/blogs", (req, res) => {
fs.readFile("./data/blogs.json", (err, data) => {
if (err) throw err
const blogs = JSON.parse(data)
res.json(blogs)
})
})
app.get("/:id/delete", (req, res) => {
const id = req.params.id
fs.readFile("./data/blogs.json", (err, data) => {
if (err) throw err
const blogs = JSON.parse(data)
const filteredBlogs = blogs.filter(blog => blog.id != id)
fs.writeFile("./data/blogs.json", JSON.stringify(filteredBlogs), (err) => {
if (err) throw err
res.redirect(req.get('referer'));
})
})
})
app.listen(8000, err => {
if (err) console.log(err);
console.log("server is running on port 8000...");
})
function id () {
return "_" + Math.random().toString(36).substr(2, 9);
}