-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
74 lines (61 loc) · 1.79 KB
/
index.js
File metadata and controls
74 lines (61 loc) · 1.79 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
const express = require("express");
const app = express();
const http = require("http");
const cors = require("cors");
const { Server } = require("socket.io");
app.use(cors());
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "*",
},
});
app.get("/", (req, res) => {
res.send("<h1>Server is running</h1>");
});
let onlineUsers = [];
const addNewUser = (userId, socketId) => {
let user = onlineUsers.find((user) => user.userId === userId);
if (!user) {
onlineUsers = [...onlineUsers, { userId, socketId }];
}
};
const removeUser = (socketId) => {
onlineUsers = onlineUsers.filter((user) => user.socketId !== socketId);
};
const getUser = (userId) => {
return onlineUsers.find((user) => user.userId === userId);
};
io.on("connection", (socket) => {
// adds the user to onlineUsers array when a new connection is established from the seller side
socket.on("new user seller", (username) => {
console.log("username", username);
if (username) {
addNewUser(username, socket.id);
}
console.log(onlineUsers);
});
// listens to buyer offer and emits a notification for the seller having the id
socket.on("buyer offer made", ({ msg, writerId }) => {
console.log({ msg, writerId });
let user = getUser(writerId);
if (user?.socketId) {
console.log(
"🚀 ~ file: index.js:53 ~ socket.on ~ user?.socketId:",
user?.socketId
);
io.to(user?.socketId).emit("buyer offer", {
message: msg,
});
}
});
// removes user from onlineUsers when user disconnects
socket.on("disconnect", () => {
removeUser(socket.id);
console.log("disconnected");
});
});
const port = process.env.PORT ?? 8080;
server.listen(port, () => {
console.log(`Listening on port ${port}`);
});