-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
84 lines (71 loc) · 2.13 KB
/
index.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
require("dotenv").config();
const express = require("express");
const app = express();
const http = require("http");
const server = http.createServer(app);
const cors = require("cors");
const db = require("./source/database");
db.connect();
const io = require("socket.io")(server, {
cors: {
origin: "*",
credentials: true,
methods: ["GET", "POST"],
transports: ["websocket", "polling"],
},
allowEIO3: true,
});
const userRoutes = require("./source/routes/users");
const chatRoutes = require("./source/routes/chats");
const {
updateChatMessages,
startChat,
updateUserStatus,
} = require("./source/helpers/users");
// app.use(express.static("public"));
// app.use(helmet());
// if (app.get("env") === "development") {
// app.use(morgan("tiny"));
// }
app.use(express.json());
app.use(cors({ credentials: true, origin: "*" }));
app.get("/", (_, res) => {
res.status(200).send("Lexar Online");
});
app.use(userRoutes);
app.use(chatRoutes);
io.on("connection", async (socket) => {
const handshakeData = socket.request;
const { email } = handshakeData._query;
updateUserStatus({ email, status: true, socketId: socket.id, io });
socket.on("join", async ({ from, to }, callback) => {
try {
const { error, chatId, text } = await startChat({
from,
to,
});
if (error) return callback({ status: "error", text });
socket.join(chatId);
callback({ status: "success" });
} catch (_) {}
});
socket.on("sendMessage", async ({ from, to, message }, callback) => {
try {
const { error, chatId, result, fromName, toSocket } = await updateChatMessages({
from,
to,
message,
});
if (error) return callback({ status: "error", text: result });
socket.to(chatId).emit("message", { from, message, time: new Date() });
io.to(toSocket).emit("notification", { from, name: fromName, message });
} catch (_) {}
});
socket.on("disconnect", () => {
updateUserStatus({ email, status: false, socketId: socket.id, io });
});
});
const PORT = process.env.PORT || 7000;
server.listen(PORT, () => {
console.log(`Server has started`);
});