fix: improved websocket usage

This commit is contained in:
Lukian 2025-04-08 22:19:06 +02:00
parent fbf7821320
commit 132b1f3c06
7 changed files with 135 additions and 79 deletions

View file

@ -1,5 +1,6 @@
const jwt = require('jsonwebtoken');
const { getConnection, getUser } = require('./mysql');
const express = require('express');
async function checkAuth(req, res, next) {
const { token } = req.body;
@ -23,6 +24,30 @@ async function checkAuth(req, res, next) {
}
}
const router = express.Router();
const sockets = new Set();
router.ws('/', function(ws, req) {
sockets.add(ws);
ws.on('close', () => {
sockets.delete(ws);
});
});
function socketsMiddleware(req, res, next) {
req.sockets = {
emit: function(data) {
for (const socket of sockets) {
socket.send(JSON.stringify(data));
}
}
};
next();
}
module.exports = {
checkAuth,
router,
socketsMiddleware,
};