-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.js
132 lines (104 loc) · 3.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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import "dotenv/config";
import "./utils/db.js";
import express from "express";
import http from 'http';
import { Server } from "socket.io";
import cors from 'cors';
import cookieParser from "cookie-parser";
import authRoute from "./routes/auth.route.js";
import userRoute from "./routes/user.route.js";
import postRoute from "./routes/post.route.js";
import chatRoute from "./routes/chat.route.js";
import messageRoute from "./routes/message.route.js";
import testRoute from "./routes/test.route.js";
const app = express();
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: true,
methods: ['GET', 'POST'],
},
});
app.use(cors({
origin: true
}));
app.use(cookieParser());
app.use(express.json());
const PORT = process.env.PORT || 3000;
app.get('/', (req, res) => {
res.send(`<h1>hey I am here working fine!</h1>`)
})
app.use("/api/auth", authRoute);
app.use("/api/user", userRoute);
app.use("/api/post", postRoute);
app.use("/api/chat", chatRoute);
app.use("/api/message", messageRoute);
app.use("/api/test", testRoute);
//// socket implementation
let onlineUsers = [];
const addUser = (userId, socketId) => {
if (!onlineUsers.some((user) => user.userId === userId)) {
onlineUsers.push({ userId, socketId });
}
};
const getUser = (userId) => {
return onlineUsers.find((user) => user.userId === userId);
};
const removeUser = async (socketId) => {
const user = onlineUsers.find((user) => user.socketId === socketId);
if (user) {
try {
await fetch(`http://localhost:8080/api/user/update-lastseen/${user.userId}`, {
method: 'POST',
});
} catch (error) {
console.error(error);
} finally {
onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId);
}
}
};
io.on("connection", (socket) => {
socket.on('newUser', (userId) => {
addUser(userId, socket.id);
io.emit('updateUserList', onlineUsers);
});
socket.on('sendMessage', ({ receiverId, data }) => {
const receiver = getUser(receiverId);
if (receiver) {
io.to(receiver.socketId).emit('getMessage', data);
}
});
socket.on('disconnect', () => {
removeUser(socket.id);
io.emit('updateUserList', onlineUsers);
});
socket.on('getUserStatus', (receiverId) => {
const receiver = getUser(receiverId);
io.to(socket.id).emit('userStatus', { online: !!receiver });
});
});
app.use((err, req, res, next) => {
const statuscode = err.statuscode || 500;
const message = err.message || "internal server error";
return res.status(statuscode).json({
success: false,
statuscode,
message,
});
});
server.listen(PORT, () => console.log(`Server running on port : ${PORT}`));
export default app;
// app.use(cors({
// origin: function (origin, callback) {
// console.log(origin);
// if (!origin) return callback(null, true);
// if (allowedOrigins.indexOf(origin) === -1) {
// const msg = 'The CORS policy for this site does not allow access from the specified Origin.';
// return callback(new Error(msg), false);
// }
// return callback(null, true);
// }
// }));
// var allowedOrigins = ["http://localhost:5173", "http://172.20.10.8:5173", "http://192.168.1.10:5173"];
// var allowedOrigins = JSON.parse(process.env.ALLOWED_ORIGINS);