diff --git a/server/package.json b/server/package.json index 094ffaa8..c7f66bba 100644 --- a/server/package.json +++ b/server/package.json @@ -28,6 +28,7 @@ "jsonwebtoken": "^9.0.2", "mongoose": "^8.5.3", "nodemailer": "^6.9.14", + "socket.io": "^4.8.0", "stripe": "^16.12.0", "uuid": "^10.0.0", "winston": "^3.14.2", diff --git a/server/src/index.ts b/server/src/index.ts index 96d91dec..7e9e0668 100644 --- a/server/src/index.ts +++ b/server/src/index.ts @@ -1,4 +1,5 @@ import express from "express"; +import { createServer } from "http"; import { connectDB } from "./config/connectDB"; import routes from "./presentation/routers/index"; import cors from "cors"; @@ -7,10 +8,13 @@ import helmet from "helmet"; import bodyParser from "body-parser"; import { webhook } from "./presentation/routers/appointment/AppointmentRoutes"; import { CLIENT_URL, NODE_ENV, PORT } from "./config/env"; +import initializeSocket from "./presentation/socket"; const port = PORT || 8080; const app = express(); +const server = createServer(app); + app.use(helmet()); app.use( cors({ @@ -27,9 +31,11 @@ app.use(express.urlencoded({ extended: true })); app.use("/api", routes); connectDB().then(() => { - app.listen(port, () => { + server.listen(port, () => { if (NODE_ENV !== "production") { console.log(`Server start listening on port: ${port}`); } }); }); + +initializeSocket(server); diff --git a/server/src/presentation/socket/index.ts b/server/src/presentation/socket/index.ts new file mode 100644 index 00000000..c3fdb2b6 --- /dev/null +++ b/server/src/presentation/socket/index.ts @@ -0,0 +1,47 @@ +import { Server } from "socket.io"; +import { Server as HTTPServer } from "http"; // Type from the HTTP server +import { CLIENT_URL } from "../../config/env"; +import logger from "../../utils/logger"; + +const initializeSocket = (server: HTTPServer) => { + const io = new Server(server, { + cors: { + origin: CLIENT_URL, + methods: ["GET", "POST"], + credentials: true, + }, + }); + + // Listen for new connections + io.on("connection", (socket) => { + console.log(`User connected: ${socket.id}`); + + // Handle joining a room + socket.on("join-room", (roomId) => { + socket.join(roomId); + logger.info(`User ${socket.id} joined room ${roomId}`); + }); + + // Handle offering WebRTC signal (from one client to another) + socket.on("offer", (offer, roomId) => { + socket.to(roomId).emit("offer", offer); + }); + + // Handle answering WebRTC offer + socket.on("answer", (answer, roomId) => { + socket.to(roomId).emit("answer", answer); + }); + + // Handle ICE candidates for WebRTC + socket.on("ice-candidate", (candidate, roomId) => { + socket.to(roomId).emit("ice-candidate", candidate); + }); + + // Handle disconnection + socket.on("disconnect", () => { + logger.warn(`User disconnected: ${socket.id}`); + }); + }); +}; + +export default initializeSocket;