-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
81 lines (51 loc) · 1.55 KB
/
index.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
const express = require("express");
const app = express();
const port = 8081;
const path = require("path");
app.use(express.urlencoded({extended: true}));
app.set("view engine" , "ejs");
app.set("views",path.join(__dirname,"/views"))
app.use(express.static(path.join(__dirname , "/public")));
const { v4: uuidv4 } = require('uuid');
const methodOverride = require("method-override");
app.use(methodOverride("_method"));
let posts = [
]
app.get("/posts", (req, res) => {
res.render("index", { posts: posts }); // Pass the posts array here
});
app.get("/posts/new", (req, res) => {
res.render("new"); // Pass the posts array here
});
app.post("/posts",(req,res)=>{
const {username , content}=req.body;
let id = uuidv4();
posts.push({id,username,content});
res.redirect("/posts");
})
app.get("/posts/:id", (req,res)=>{
let {id}=req.params;
let post = posts.find((p)=> id===p.id);
res.render("show.ejs",{post});
})
// to update any post
app.patch("/posts/:id",(req,res)=>{
let {id}= req.params;
let newContent = req.body.content;
let post = posts.find((p)=> id===p.id);
post.content= newContent;
res.redirect("/posts");
})
app.get("/posts/:id/edit",(req,res)=>{
let {id}= req.params;
let post = posts.find((p)=> id===p.id);
res.render("edit",{post});
})
app.delete("/posts/:id", (req, res) => {
let { id } = req.params;
posts = posts.filter((p) => id !== p.id);
res.redirect("/posts");
});
app.listen(port,()=>{
console.log(`listening on port ${port}`);
});