-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
108 lines (89 loc) · 2.73 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
const http = require("http");
const express = require("express");
const cors = require("cors");
const mongoose = require("mongoose");
const { Server } = require("socket.io");
require("dotenv").config();
const app = express();
const PORT = process.env.PORT || 9090;
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
app.use(cors());
const customerRoutes = require("./routes/customer");
const productRoutes = require("./routes/product");
const orderRoutes = require("./routes/order");
const messageRotues = require("./routes/message");
const messageController = require("./controllers/message");
const Customer = require("./models/customer");
app.use("/auth", customerRoutes);
app.use("/products", productRoutes);
app.use("/orders", orderRoutes);
app.use("/message", messageRotues);
const server = http.createServer(app);
const io = new Server(server, {
cors: {
origin: "http://localhost:3000",
methods: ["GET", "POST"],
},
});
// to track user id
const userSocketMap = {};
io.on("connection", async (socket) => {
console.log("A user connected:", socket.id);
socket.on("register_user", (userId) => {
userSocketMap[userId] = socket.id;
});
socket.on(
"new_message",
async ({ message, senderId, recipient, name, to }) => {
const savedMessage = await messageController.saveMessage({
message,
senderId,
recipient,
name,
to: to ? to : undefined,
});
try {
const sender = await Customer.findById({ _id: senderId });
await sender.setIsStartedChatting();
await sender.addMessage(savedMessage._id);
const recipientUser = await Customer.findById(recipient);
await recipientUser.setIsStartedChatting();
} catch (err) {
console.log("got an error", err);
}
const senderSocketId = userSocketMap[senderId];
if (senderSocketId) {
io.to(senderSocketId).emit("message_received", savedMessage);
}
const recipientSocketId = userSocketMap[recipient];
if (recipientSocketId) {
io.to(recipientSocketId).emit("message_received", savedMessage);
}
}
);
socket.on("disconnect", () => {
// delete the user from the map ids.
for (let userId in userSocketMap) {
if (userSocketMap[userId] === socket.id) {
delete userSocketMap[userId];
break;
}
}
console.log("user disconnected", socket.id);
});
});
app.get("/", (req, res) => {
res.json({ message: "Welcome to Laundry Service API" });
});
server.listen(PORT, () => {
console.log("Server is listening on PORT " + PORT);
});
mongoose
.connect(process.env.mongoURI)
.then(() => {
console.log("connected");
})
.catch((err) => {
console.log(err.message);
});