-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
85 lines (72 loc) · 2.09 KB
/
index.js
File metadata and controls
85 lines (72 loc) · 2.09 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
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
const express = require("express");
const app = express();
const port = 4040;
const path = require("path");
const mongoose = require('mongoose');
const Chat = require("./models/chat.js")
const methodOverride = require('method-override');
main().then(()=>{
console.log("Connection Succesfull")
})
.catch(err => console.log(err));
async function main() {
await mongoose.connect('mongodb://127.0.0.1:27017/whatsapp');
}
app.use(express.urlencoded({extended: true}))
// // override with POST having ?_method=DELETE
app.use(methodOverride('_method'))
app.use(express.static(path.join(__dirname,"public")))
app.set("view engine","ejs")
app.set("views",path.join(__dirname,"views"))
// INDEX ROUTE
app.get("/chats",async (req,res) =>{
let chats = await Chat.find()
console.log(chats)
res.render("index.ejs",{chats});
});
// NEW ROUTE
app.get("/chats/new",(req,res)=>{
res.render("new.ejs")
});
// CREATE ROUTE
app.post("/chats",(req,res)=>{
let { from,to ,msg}= req.body
let newChat = new Chat({
from : from,
to : to,
msg : msg,
created_at : new Date(),
})
newChat
.save().then((res)=>{
console.log("New chat was saved")
})
.catch(err => console.log(err));
res.redirect("/chats");
});
// EDIT ROUTE
app.get("/chats/:id/edit",async(req,res)=>{
let {id} = req.params
let chat = await Chat.findById(id)
res.render("edit.ejs",{chat})
})
// UPDATE ROUTE
app.put("/chats/:id",async(req,res)=>{
let {id} = req.params
let {msg: newMsg} = req.body
let updatedChat = await Chat.findByIdAndUpdate(id,{msg: newMsg},{runValidators: true,new: true})
res.redirect("/chats")
})
// DESTROY ROUTE
app.delete("/chats/:id",async(req,res)=>{
let {id} = req.params
let deletedChat = await Chat.findByIdAndDelete(id)
console.log(deletedChat)
res.redirect("/chats")
})
app.get("/",(req,res) =>{
res.send("Serving is working......");
})
app.listen(port,() => {
console.log(`listening to Port :${port}`);
})