-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
93 lines (72 loc) · 2.25 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
const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const logger = require('morgan');
require('./models/db.model')()
const auth = require('./router/auth.route')
const message = require('./router/messaging.route')
const app = express();
const errorHandler = require('./middlewares/errorHandler');
const cors = require('cors');
const http = require('http').createServer(app)
const { authModel } = require('./models/auth.model');
const io = require('socket.io')(http, {
cors: {
origin: '*'
}
})
//middleware
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(cors())
app.use(express.static(path.join(__dirname, 'public/messaging')));
//Routes
app.use('/api/auth', auth)
app.use('/api/msg', message)
/**
* Listen on provided port, on all network interfaces.
*/
//Socket connection
// const io = require("socket.io")(http, {
// cors: {
// origin: "http://localhost:3000",
// methods: ["GET", "POST"]
// }
// });
io.on('connection', (socket) => {
socket.on('online', async (data) => {
await authModel.updateOne({ _id: data.id }, {
$set: {
isActive: true
}
})
console.log(data.id+"online")
socket.broadcast.emit('online',"online")
socket.on("disconnect", async () => {
console.log("offline")
await authModel.updateOne({ _id: data.id }, {
$set: {
isActive: false,
lastSeen: Date.now()
}
})
socket.broadcast.emit('offline',"offline")
})
})
socket.on('join', (data) => {
socket.join(data.id)
console.log("join room "+data.id)
socket.on('send', (data) => {
socket.broadcast.to(data.senderid).emit('notifyme', data.id)
socket.broadcast.to(data.senderid).emit('recieved', data);
})
})
});
http.listen(process.env.PORT || 3000, () => {
console.log('listening on *:3000');
});
//handle all routes error
app.use(errorHandler)
// module.exports = app;