diff --git a/app.js b/app.js index 1486c80..6d8b9c3 100644 --- a/app.js +++ b/app.js @@ -9,7 +9,7 @@ const securityKeyMiddleware = require("./middlewares/securityKeyMiddleware"); const app = express(); const server = http.createServer(app); -const wss = new WebSocket.Server({ server }); +const wss = new WebSocket.Server({ server , path: '/ws'}); app.use(express.json()); app.use(securityKeyMiddleware); @@ -28,6 +28,15 @@ exports.sendMessageToSocket = (connectionId, data) => { }); } +exports.isConnected = (connectionId) => { + wss.clients.forEach((client) => { + if(client.connectionId === connectionId){ + return true; + } + }); + return false; +} + exports.closeConnection = (connectionId) => { wss.clients.forEach((client) => { if(client.connectionId === connectionId){ diff --git a/controllers/khokhaEntryController.js b/controllers/khokhaEntryController.js index bbfa347..8ae7e8b 100644 --- a/controllers/khokhaEntryController.js +++ b/controllers/khokhaEntryController.js @@ -4,6 +4,12 @@ const KhokhaEntryModel = require('../models/KhokhaEntryModel'); // TODO: Implement these controllers exports.addNewEntry = async (req, res, next) => { try { + if(ws.isConnected(req.body.connectionId)===false){ + return res.json({ + success: false, + message: "Socket is not connected" + }); + } const entry = await KhokhaEntryModel.create({ outlookEmail: req.body.outlookEmail, name: req.body.name, @@ -17,11 +23,11 @@ exports.addNewEntry = async (req, res, next) => { destination: req.body.destination, }); - console.log(entry); + ws.sendMessageToSocket(req.body.connectionId, { success: true, message: "Entry Added to database!", - entryId: entry._id + data: entry }); ws.closeConnection(req.body.connectionId); @@ -37,6 +43,13 @@ exports.addNewEntry = async (req, res, next) => { exports.closeEntry = async (req, res, next) => { const entryId = req.params.id; try { + if(ws.isConnected(req.body.connectionId)===false){ + return res.json({ + success: false, + message: "Socket is not connected" + }); + } + const entry = await KhokhaEntryModel.findById(entryId); if (!entry) { @@ -64,7 +77,7 @@ exports.closeEntry = async (req, res, next) => { }); } - const response = await KhokhaEntryModel.findByIdAndUpdate(entryId, { + const newEntry = await KhokhaEntryModel.findByIdAndUpdate(entryId, { inTime: Date(), isClosed: true }, {new: true}); @@ -72,11 +85,10 @@ exports.closeEntry = async (req, res, next) => { ws.sendMessageToSocket(req.body.connectionId, { success: true, message: "Entry Closed Successfully!", + data: newEntry }); ws.closeConnection(req.body.connectionId); - console.log(response); - return res.json({ success: true, message: "Entry Closed Successfully!"