-
Notifications
You must be signed in to change notification settings - Fork 1
/
app.js
100 lines (78 loc) · 2.66 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
const express = require("express"),
app = express(),
mongoose = require("mongoose"),
server = require("http").createServer(app),
path = require('path'),
bodyParser = require("body-parser"),
io = require('socket.io')(server),
User = require("./models/userSchema"),
Message = require("./models/messageSchema"),
connect = require("./dbconnection"),
port = process.env.PORT||8080;
connect.then(db => {
console.log("connected to the database server");
}).catch(err=>console.log(err))
app.set("view engine", "ejs")
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(express.static(path.join(__dirname,'/public')))
app.get("/", (req, res)=>{
res.render("pages/home")
})
app.post("/chat", function(req, res){
let chatRoom = req.body.chatroom
var user = req.body.user
res.render("pages/chatpage", {chatRoom:chatRoom, user:user})
})
io.on('connection', (socket) => {
console.log(`a user connected`);
socket.on("welcome", data=>{
console.log(data)
socket.emit("welcome", `glad to see you here ${data.user}!!`);
})
socket.broadcast.emit('connected',`A new user joined`)
socket.on('disconnect', () => {
console.log('user disconnected');
io.emit('disconnected', 'Someone just left')
});
socket.on('chat message', data => {
let newUser
let {msg, user} = data
io.emit('chat message', data);
let newmsg = new Message(
{
_id: new mongoose.Types.ObjectId(),
message: msg
})
let msgID = newmsg._id
User.findOne({sender: user}, (err, found)=>{
if(err) console.log("ERROR: ",err)
else if( found!=null) {
newmsg.sender = found._id
found.messages.push(msgID)
found.save((err, saved)=>{
if(err) console.log(err)
else console.log(saved)
})
}
else {
newUser = new User({_id: new mongoose.Types.ObjectId(), sender: user})
newmsg.sender = newUser._id
newUser.messages.push(msgID)
newUser.save((err, saved)=>{
if(err) console.log(err)
else console.log("saved user: "+ saved)
})
}
newmsg.save((err, savedMsg)=>{
if(err) console.log(err)
else console.log(savedMsg)
})
})
});
});
server.listen(port, ()=>{
console.log("Server listening on port: "+ port);
})