-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
150 lines (134 loc) · 4.18 KB
/
server.js
File metadata and controls
150 lines (134 loc) · 4.18 KB
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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
import express from "express";
import cors from "cors";
import "dotenv/config";
import connectDB from "./db/mongooseDB.js";
import { inngest, functions } from "./utils/inngest.utils.js";
import { serve } from "inngest/express";
import usersRouter from "./routes/user.routes.js";
import postsRouter from "./routes/post.routes.js";
import storysRouter from "./routes/story.routes.js";
import messagesRouter from "./routes/message.routes.js";
import commentsRouter from "./routes/comment.routes.js";
import notificationsRouter from "./routes/notification.routes.js";
import http from "http";
import { Server } from "socket.io";
import cookieParser from "cookie-parser";
import jwt from "jsonwebtoken";
import helmet from "helmet";
import compression from "compression";
//#region CONSTANTS
const app = express();
const PORT = process.env.PORT || 4000;
const allowedOrigins = process.env.CORS_ORIGIN.split(","); // split comma-separated string
//#endregion
//#region MIDDLEWARE
app.use(
cors({
origin: allowedOrigins,
methods: ["PATCH", "POST", "PUT", "GET", "DELETE", "OPTIONS"],
allowedHeaders: [
"Content-Type",
"Authorization",
"Access-Control-Allow-Headers",
// "Access-Control-Allow-Origin",
],
credentials: true,
// optionsSuccessStatus: 200,
}),
);
app.use(helmet());
app.use(compression());
app.use(express.json());
app.use(cookieParser());
app.use(
express.urlencoded({
extended: true,
limit: "16kb",
}),
);
//INFO: The clerkMiddleware() function checks the request's cookies and headers for a session JWT and, if found, attaches the object to the request object under the auth key.
// app.use(clerkMiddleware());
//#endregion
//#region ENDPOINTS
app.get("/", (req, res) => {
res.send("Server is running");
});
app.use("/api/inngest", serve({ client: inngest, functions }));
app.use("/api/v1/user", usersRouter);
app.use("/api/v1/post", postsRouter);
app.use("/api/v1/story", storysRouter);
app.use("/api/v1/message", messagesRouter);
app.use("/api/v1/comment", commentsRouter);
app.use("/api/v1/notification", notificationsRouter);
//#endregion
//#region Socket IO;
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: allowedOrigins,
// origin: "https://devdad-knect.vercel.app",
methods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"],
credentials: true,
},
});
const onlineUsers = new Map();
io.on("connection", (socket) => {
const token = socket.handshake.auth?.token;
// if (!userId) return;
if (!token) {
console.log("Socket connection rejected: no token");
socket.disconnect();
return;
}
try {
// Verify the JWT
const decoded = jwt.verify(token, process.env.ACCESS_TOKEN_SECRET);
const userId = decoded._id; // assuming your JWT payload has {_id: "..."}
console.log(`Socket connected: ${socket.id} (user: ${userId})`);
const userSet = onlineUsers.get(userId) ?? new Set();
userSet.add(socket.id);
onlineUsers.set(userId, userSet);
// Receive messages
socket.on("private_message", (payload) => {
const { to_user_id, text } = payload;
console.log(`Message from ${userId} to ${to_user_id}: ${text}`);
// Emit to recipient if online
const destSockets = onlineUsers.get(to_user_id);
if (destSockets) {
for (const sid of destSockets) {
io.to(sid).emit("receive_message", {
from_user_id: userId,
to_user_id,
text,
});
}
}
});
socket.on("disconnect", () => {
console.log(`Socket disconnected: ${socket.id}`);
const userSet = onlineUsers.get(userId);
if (userSet) {
userSet.delete(socket.id);
if (userSet.size === 0) onlineUsers.delete(userId);
else onlineUsers.set(userId, userSet);
}
});
} catch (error) {
console.log("Socket connection rejected: invalid token");
socket.disconnect();
}
});
app.set("io", io);
app.set("onlineUsers", onlineUsers);
//#endregion
//#region MONGO CONNECTION
connectDB()
.then(
server.listen(PORT, () => {
console.log(`Server is running on port: ${PORT}`);
}),
)
.catch((err) => {
console.log(`MongoDB Connection Error`, err);
});
//#endregion