-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
152 lines (125 loc) · 3.88 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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
import express from "express";
import { connectDB } from "./utils/features.js";
import dotenv from "dotenv";
import { errorMiddleware } from "./middlewares/error.js";
import cookieParser from "cookie-parser";
import { Server } from "socket.io";
import { createServer } from "http";
import { v4 as uuid } from "uuid";
import cors from "cors";
import { v2 as cloudinary } from "cloudinary";
import {
CHAT_JOINED,
CHAT_LEFT,
NEW_MESSAGE,
NEW_MESSAGE_ALERT,
ONLINE_USERS,
START_TYPING,
STOP_TYPING,
} from "./constants/events.js";
import { getSockets } from "./lib/helper.js";
import { Message } from "./models/message.js";
import { corsOption } from "./constants/config.js";
import { socketAuthenticator } from "./middlewares/auth.js";
import userRoute from "./routes/user.js";
import chatRoute from "./routes/chat.js";
import adminRoute from "./routes/admin.js";
dotenv.config({
path: "./.env",
});
const mongoURI = process.env.MONGO_URI;
const port = process.env.PORT || 3000;
const envMode = process.env.NODE_ENV.trim() || "PRODUCTION";
const adminSecretKey = process.env.ADMIN_SECRET_KEY || "adsasdsdfsdfsdfd";
const userSocketIDs = new Map();
const onlineUsers = new Set();
connectDB(mongoURI);
cloudinary.config({
cloud_name: process.env.CLOUDINARY_CLOUD_NAME,
api_key: process.env.CLOUDINARY_API_KEY,
api_secret: process.env.CLOUDINARY_API_SECRET,
});
const app = express();
const server = createServer(app);
const io = new Server(server, {
cors: corsOption,
});
app.set("io", io);
// Using Middlewares Here
app.use(express.json());
app.use(cookieParser());
app.use(cors(corsOption));
app.use("/api/v1/user", userRoute);
app.use("/api/v1/chat", chatRoute);
app.use("/api/v1/admin", adminRoute);
app.get("/", (req, res) => {
res.send("Hello World");
});
io.use((socket, next) => {
cookieParser()(
socket.request,
socket.request.res,
async (err) => await socketAuthenticator(err, socket, next)
);
});
io.on("connection", (socket) => {
const user = socket.user;
userSocketIDs.set(user._id.toString(), socket.id);
socket.on(NEW_MESSAGE, async ({ chatId, members, message }) => {
const messageForRealTime = {
content: message,
_id: uuid(),
sender: {
_id: user._id,
name: user.name,
},
chat: chatId,
createdAt: new Date().toISOString(),
};
const messageForDB = {
content: message,
sender: user._id,
chat: chatId,
};
const membersSocket = getSockets(members);
io.to(membersSocket).emit(NEW_MESSAGE, {
chatId,
message: messageForRealTime,
});
io.to(membersSocket).emit(NEW_MESSAGE_ALERT, { chatId });
try {
await Message.create(messageForDB);
} catch (error) {
throw new Error(error);
}
});
socket.on(START_TYPING, ({ members, chatId }) => {
const membersSockets = getSockets(members);
socket.to(membersSockets).emit(START_TYPING, { chatId });
});
socket.on(STOP_TYPING, ({ members, chatId }) => {
const membersSockets = getSockets(members);
socket.to(membersSockets).emit(STOP_TYPING, { chatId });
});
socket.on(CHAT_JOINED, ({ userId, members }) => {
onlineUsers.add(userId.toString());
const membersSocket = getSockets(members);
io.to(membersSocket).emit(ONLINE_USERS, Array.from(onlineUsers));
});
socket.on(CHAT_LEFT, ({ userId, members }) => {
onlineUsers.delete(userId.toString());
const membersSocket = getSockets(members);
io.to(membersSocket).emit(ONLINE_USERS, Array.from(onlineUsers));
});
console.log(onlineUsers)
socket.on("disconnect", () => {
userSocketIDs.delete(user._id.toString());
onlineUsers.delete(user._id.toString());
socket.broadcast.emit(ONLINE_USERS, Array.from(onlineUsers));
});
});
app.use(errorMiddleware);
server.listen(port, () => {
console.log(`Server is running on port ${port} in ${envMode} Mode`);
});
export { envMode, adminSecretKey, userSocketIDs };