-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (45 loc) · 1.36 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
const express = require('express');
const http = require('http');
const dotenv = require('dotenv');
dotenv.config();
const socketio = require('socket.io');
const app = express();
const server = http.createServer(app);
const io = socketio(server);
const connect = require('./config/database-config');
const Chat = require('./models/chats');
io.on('connection', (socket) => {
// console.log('a user connected', socket.id);
socket.on('join_room', (data) => {
socket.join(data.roomId);
console.log('user joined room', data.roomId);
});
socket.on('msg_send',async (data) => {
console.log(data);
// io.emit('msg_rcvd', data);
const chat = await Chat.create({
content: data.msg,
user1: data.username,
roomId: data.roomId,
});
io.to(data.roomId).emit('msg_rcvd', data);
});
socket.on('typing', (data) => {
socket.broadcast.to(data.roomId).emit('someone_typing');
});
});
app.set('view engine', 'ejs');
app.use('/', express.static(__dirname + '/public'));
app.get('/chat/:roomId',async (req, res) => {
const chats = await Chat.find({roomId:req.params.roomId}).select('content user1');
res.render('index', {
name: 'shubham',
id: req.params.roomId,
chats: chats,
});
});
server.listen(3000, async () => {
console.log('server started');
await connect();
console.log('mongodb connected ')
});