-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
65 lines (53 loc) · 1.86 KB
/
server.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
const express = require('express');
const http = require('http');
const socketIO = require('socket.io');
const cors = require('cors');
const connectDB = require('./config/db');
const fileRoutes = require('./routes/fileRoutes');
const userRoutes = require('./routes/userRoutes');
const chatRoutes = require('./routes/chatRoutes');
const authMiddleware = require('./middleware/authMiddleware'); // Middleware to authenticate users
require('dotenv').config();
const app = express();
const server = http.createServer(app);
const io = socketIO(server, { cors: { origin: '*' } });
// Pass io to request object
app.use((req, res, next) => {
req.io = io; // Attach the io instance to the request object
next();
});
// Connect to MongoDB
connectDB();
// Middleware
//app.use(cors());
app.use(express.json());
// Routes
app.use('/api/files', fileRoutes);
app.use('/api/users', userRoutes);
app.use('/api/chat', chatRoutes); // Protect chat routes with authentication
// Socket.IO Logic
io.on('connection', (socket) => {
console.log('A user connected:', socket.id);
// Join specific peer rooms based on their unique peer ID
socket.on('join', (peerId) => {
socket.join(peerId);
console.log(`User with peer ID ${peerId} joined their room`);
});
// Handle real-time chat messages
socket.on('chat-message', ({ sender, receiver, message }) => {
console.log(`Message from ${sender} to ${receiver}: ${message}`);
// Emit the message to the receiver's room
io.to(receiver).emit('receive-message', {
sender,
message,
timestamp: new Date(),
});
});
socket.on('disconnect', () => {
console.log('User disconnected:', socket.id);
});
});
// Start the server
server.listen(process.env.PORT || 5000, () => {
console.log(`Server running on port ${process.env.PORT || 5000}`);
});