-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathindex.js
More file actions
62 lines (52 loc) · 1.8 KB
/
index.js
File metadata and controls
62 lines (52 loc) · 1.8 KB
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
import express from "express";
import bodyParser from "body-parser";
import { v4 as uuidv4 } from 'uuid';
const app=express();
const port =3000;
let postList=[];
app.use(express.static("public"));
app.use(bodyParser.urlencoded({extended:true}));
app.get("/",(req,res)=>{
postList=[];
res.render("index.ejs",{posts:postList});
});
app.post("/submit",(req,res)=>{
console.log(req.body);
const newPost={
id: uuidv4(), //this import function gives a unique id to each blog messege
firstName: req.body["fName"],
lastName: req.body["lName"],
userName: req.body["username"],
msg: req.body["message"],
timestamp: new Date().toLocaleString()
};
postList.unshift(newPost); //push at the beginning of arary
res.render("index.ejs",{posts:postList});
console.log(postList);
});
app.post("/delete",(req,res)=>{
const postId=req.body.id;
postList=postList.filter(post=>post.id!==postId); //removes the id delet button
res.render("index.ejs",{posts:postList});
});
app.get("/edit", (req, res) => {
const postId = req.query.id;
const postToEdit = postList.find(post => post.id === postId);
res.render("partials/post-edit.ejs", {post: postToEdit});
});
app.post("/update", (req, res) => {
const postId = req.body.id;
const updatedPost = {
id: postId,
firstName: req.body["fName"],
lastName: req.body["lName"],
userName: req.body["username"],
msg: req.body["message"],
timestamp: postList.find(post => post.id === postId).timestamp
};
postList = postList.map(post => post.id === postId ? updatedPost : post);
res.render("index.ejs", {posts: postList});
});
app.listen(process.env.PORT || port,()=>{
console.log(`Listening to ${port}`);
});